Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

[py3] Ported django.utils.encoding.

* Renamed smart_unicode to smart_text (but kept the old name under
  Python 2 for backwards compatibility).
* Renamed smart_str to smart_bytes.
* Re-introduced smart_str as an alias for smart_text under Python 3
  and smart_bytes under Python 2 (which is backwards compatible).
  Thus smart_str always returns a str objects.
* Used the new smart_str in a few places where both Python 2 and 3
  want a str.
  • Loading branch information...
commit c5ef65bcf324f4c90b53be90f4aec069a68e8c59 1 parent ee19171
@aaugustin aaugustin authored
Showing with 629 additions and 583 deletions.
  1. +4 −4 django/contrib/admin/actions.py
  2. +4 −4 django/contrib/admin/filters.py
  3. +4 −4 django/contrib/admin/helpers.py
  4. +3 −3 django/contrib/admin/models.py
  5. +29 −29 django/contrib/admin/options.py
  6. +6 −6 django/contrib/admin/templatetags/admin_list.py
  7. +9 −9 django/contrib/admin/util.py
  8. +3 −3 django/contrib/admin/views/main.py
  9. +4 −4 django/contrib/admin/widgets.py
  10. +2 −2 django/contrib/admindocs/utils.py
  11. +4 −4 django/contrib/auth/hashers.py
  12. +14 −14 django/contrib/auth/tests/forms.py
  13. +2 −2 django/contrib/auth/tests/views.py
  14. +2 −2 django/contrib/comments/forms.py
  15. +2 −2 django/contrib/comments/managers.py
  16. +2 −2 django/contrib/comments/templatetags/comments.py
  17. +2 −2 django/contrib/contenttypes/generic.py
  18. +2 −2 django/contrib/contenttypes/management.py
  19. +5 −5 django/contrib/contenttypes/models.py
  20. +8 −8 django/contrib/databrowse/datastructures.py
  21. +2 −2 django/contrib/databrowse/plugins/calendars.py
  22. +2 −2 django/contrib/databrowse/plugins/fieldchoices.py
  23. +2 −2 django/contrib/formtools/wizard/storage/base.py
  24. +2 −2 django/contrib/gis/sitemaps/views.py
  25. +2 −2 django/contrib/humanize/templatetags/humanize.py
  26. +2 −2 django/contrib/localflavor/au/forms.py
  27. +4 −4 django/contrib/localflavor/br/forms.py
  28. +2 −2 django/contrib/localflavor/ca/forms.py
  29. +2 −2 django/contrib/localflavor/ch/forms.py
  30. +2 −2 django/contrib/localflavor/cl/forms.py
  31. +2 −2 django/contrib/localflavor/fr/forms.py
  32. +2 −2 django/contrib/localflavor/hk/forms.py
  33. +3 −3 django/contrib/localflavor/hr/forms.py
  34. +5 −5 django/contrib/localflavor/id/forms.py
  35. +3 −3 django/contrib/localflavor/in_/forms.py
  36. +2 −2 django/contrib/localflavor/is_/forms.py
  37. +2 −2 django/contrib/localflavor/it/forms.py
  38. +3 −3 django/contrib/localflavor/it/util.py
  39. +2 −2 django/contrib/localflavor/nl/forms.py
  40. +3 −3 django/contrib/localflavor/pt/forms.py
  41. +2 −2 django/contrib/localflavor/tr/forms.py
  42. +2 −2 django/contrib/localflavor/us/forms.py
  43. +10 −10 django/contrib/markup/templatetags/markup.py
  44. +7 −7 django/contrib/messages/storage/base.py
  45. +2 −2 django/contrib/sessions/backends/db.py
  46. +3 −3 django/contrib/staticfiles/management/commands/collectstatic.py
  47. +3 −3 django/contrib/staticfiles/management/commands/findstatic.py
  48. +5 −5 django/contrib/staticfiles/storage.py
  49. +6 −6 django/contrib/syndication/views.py
  50. +3 −3 django/core/cache/backends/base.py
  51. +2 −2 django/core/context_processors.py
  52. +3 −3 django/core/exceptions.py
  53. +3 −3 django/core/files/base.py
  54. +2 −2 django/core/files/storage.py
  55. +2 −2 django/core/files/uploadedfile.py
  56. +4 −4 django/core/handlers/base.py
  57. +3 −3 django/core/handlers/wsgi.py
  58. +6 −6 django/core/mail/message.py
  59. +2 −2 django/core/management/commands/createcachetable.py
  60. +2 −2 django/core/management/commands/loaddata.py
  61. +1 −1  django/core/serializers/base.py
  62. +1 −1  django/core/serializers/json.py
  63. +7 −7 django/core/serializers/python.py
  64. +1 −1  django/core/serializers/pyyaml.py
  65. +9 −9 django/core/serializers/xml_serializer.py
  66. +6 −6 django/core/signing.py
  67. +6 −6 django/core/urlresolvers.py
  68. +3 −3 django/core/validators.py
  69. +5 −5 django/db/backends/__init__.py
  70. +9 −9 django/db/backends/oracle/base.py
  71. +5 −5 django/db/models/base.py
  72. +7 −7 django/db/models/fields/__init__.py
  73. +2 −2 django/db/models/fields/files.py
  74. +3 −3 django/db/models/fields/related.py
  75. +3 −3 django/db/models/options.py
  76. +3 −3 django/db/models/related.py
  77. +2 −2 django/db/models/sql/query.py
  78. +3 −3 django/db/models/sql/subqueries.py
  79. +10 −10 django/forms/fields.py
  80. +10 −10 django/forms/forms.py
  81. +5 −5 django/forms/models.py
  82. +6 −6 django/forms/util.py
  83. +21 −21 django/forms/widgets.py
  84. +12 −12 django/http/__init__.py
  85. +5 −5 django/http/multipartparser.py
  86. +6 −6 django/template/base.py
  87. +2 −2 django/template/debug.py
  88. +9 −9 django/template/defaultfilters.py
  89. +3 −3 django/template/defaulttags.py
  90. +3 −3 django/templatetags/l10n.py
  91. +5 −5 django/test/client.py
  92. +2 −2 django/test/html.py
  93. +4 −4 django/test/testcases.py
  94. +3 −3 django/utils/_os.py
  95. +2 −2 django/utils/cache.py
  96. +4 −4 django/utils/crypto.py
  97. +3 −3 django/utils/dateformat.py
  98. +42 −24 django/utils/encoding.py
  99. +6 −6 django/utils/feedgenerator.py
  100. +11 −11 django/utils/html.py
  101. +5 −5 django/utils/http.py
  102. +12 −12 django/utils/text.py
  103. +2 −2 django/utils/translation/__init__.py
  104. +3 −3 django/utils/translation/trans_null.py
  105. +3 −3 django/utils/tzinfo.py
  106. +4 −4 django/views/debug.py
  107. +3 −3 django/views/generic/dates.py
  108. +3 −3 django/views/i18n.py
  109. +1 −1  docs/howto/custom-model-fields.txt
  110. +1 −1  docs/ref/databases.txt
  111. +2 −2 docs/ref/models/instances.txt
  112. +1 −1  docs/ref/settings.txt
  113. +12 −12 docs/ref/unicode.txt
  114. +39 −11 docs/ref/utils.txt
  115. +1 −1  docs/releases/1.5.txt
  116. +1 −1  docs/topics/cache.txt
  117. +2 −2 docs/topics/serialization.txt
  118. +4 −4 tests/modeltests/field_subclassing/fields.py
  119. +2 −2 tests/modeltests/field_subclassing/models.py
  120. +30 −30 tests/regressiontests/admin_filters/tests.py
  121. +1 −1  tests/regressiontests/admin_views/admin.py
  122. +3 −3 tests/regressiontests/cache/tests.py
  123. +7 −7 tests/regressiontests/forms/tests/extra.py
  124. +2 −2 tests/regressiontests/signing/tests.py
  125. +3 −3 tests/regressiontests/staticfiles_tests/tests.py
View
8 django/contrib/admin/actions.py
@@ -7,7 +7,7 @@
from django.contrib.admin.util import get_deleted_objects, model_ngettext
from django.db import router
from django.template.response import TemplateResponse
-from django.utils.encoding import force_unicode
+from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy, ugettext as _
def delete_selected(modeladmin, request, queryset):
@@ -42,7 +42,7 @@ def delete_selected(modeladmin, request, queryset):
n = queryset.count()
if n:
for obj in queryset:
- obj_display = force_unicode(obj)
+ obj_display = force_text(obj)
modeladmin.log_deletion(request, obj, obj_display)
queryset.delete()
modeladmin.message_user(request, _("Successfully deleted %(count)d %(items)s.") % {
@@ -52,9 +52,9 @@ def delete_selected(modeladmin, request, queryset):
return None
if len(queryset) == 1:
- objects_name = force_unicode(opts.verbose_name)
+ objects_name = force_text(opts.verbose_name)
else:
- objects_name = force_unicode(opts.verbose_name_plural)
+ objects_name = force_text(opts.verbose_name_plural)
if perms_needed or protected:
title = _("Cannot delete %(name)s") % {"name": objects_name}
View
8 django/contrib/admin/filters.py
@@ -9,7 +9,7 @@
from django.db import models
from django.core.exceptions import ImproperlyConfigured
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
@@ -195,7 +195,7 @@ def choices(self, cl):
}
for pk_val, val in self.lookup_choices:
yield {
- 'selected': self.lookup_val == smart_unicode(pk_val),
+ 'selected': self.lookup_val == smart_text(pk_val),
'query_string': cl.get_query_string({
self.lookup_kwarg: pk_val,
}, [self.lookup_kwarg_isnull]),
@@ -272,7 +272,7 @@ def choices(self, cl):
}
for lookup, title in self.field.flatchoices:
yield {
- 'selected': smart_unicode(lookup) == self.lookup_val,
+ 'selected': smart_text(lookup) == self.lookup_val,
'query_string': cl.get_query_string({
self.lookup_kwarg: lookup}),
'display': title,
@@ -381,7 +381,7 @@ def choices(self, cl):
if val is None:
include_none = True
continue
- val = smart_unicode(val)
+ val = smart_text(val)
yield {
'selected': self.lookup_val == val,
'query_string': cl.get_query_string({
View
8 django/contrib/admin/helpers.py
@@ -9,7 +9,7 @@
from django.db.models.fields.related import ManyToManyRel
from django.forms.util import flatatt
from django.template.defaultfilters import capfirst
-from django.utils.encoding import force_unicode, smart_unicode
+from django.utils.encoding import force_text, smart_text
from django.utils.html import conditional_escape, format_html
from django.utils.safestring import mark_safe
from django.utils import six
@@ -122,7 +122,7 @@ def __init__(self, form, field, is_first):
def label_tag(self):
classes = []
- contents = conditional_escape(force_unicode(self.field.label))
+ contents = conditional_escape(force_text(self.field.label))
if self.is_checkbox:
classes.append('vCheckboxLabel')
else:
@@ -166,7 +166,7 @@ def label_tag(self):
label = self.field['label']
return format_html('<label{0}>{1}:</label>',
flatatt(attrs),
- capfirst(force_unicode(label)))
+ capfirst(force_text(label)))
def contents(self):
from django.contrib.admin.templatetags.admin_list import _boolean_icon
@@ -182,7 +182,7 @@ def contents(self):
if boolean:
result_repr = _boolean_icon(value)
else:
- result_repr = smart_unicode(value)
+ result_repr = smart_text(value)
if getattr(attr, "allow_tags", False):
result_repr = mark_safe(result_repr)
else:
View
6 django/contrib/admin/models.py
@@ -5,7 +5,7 @@
from django.contrib.auth.models import User
from django.contrib.admin.util import quote
from django.utils.translation import ugettext_lazy as _
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
ADDITION = 1
CHANGE = 2
@@ -13,7 +13,7 @@
class LogEntryManager(models.Manager):
def log_action(self, user_id, content_type_id, object_id, object_repr, action_flag, change_message=''):
- e = self.model(None, None, user_id, content_type_id, smart_unicode(object_id), object_repr[:200], action_flag, change_message)
+ e = self.model(None, None, user_id, content_type_id, smart_text(object_id), object_repr[:200], action_flag, change_message)
e.save()
class LogEntry(models.Model):
@@ -34,7 +34,7 @@ class Meta:
ordering = ('-action_time',)
def __repr__(self):
- return smart_unicode(self.action_time)
+ return smart_text(self.action_time)
def __unicode__(self):
if self.action_flag == ADDITION:
View
58 django/contrib/admin/options.py
@@ -28,7 +28,7 @@
from django.utils.text import capfirst, get_text_list
from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
-from django.utils.encoding import force_unicode
+from django.utils.encoding import force_text
HORIZONTAL, VERTICAL = 1, 2
# returns the <ul> class for a given radio_admin field
@@ -520,7 +520,7 @@ def log_addition(self, request, object):
user_id = request.user.pk,
content_type_id = ContentType.objects.get_for_model(object).pk,
object_id = object.pk,
- object_repr = force_unicode(object),
+ object_repr = force_text(object),
action_flag = ADDITION
)
@@ -535,7 +535,7 @@ def log_change(self, request, object, message):
user_id = request.user.pk,
content_type_id = ContentType.objects.get_for_model(object).pk,
object_id = object.pk,
- object_repr = force_unicode(object),
+ object_repr = force_text(object),
action_flag = CHANGE,
change_message = message
)
@@ -560,7 +560,7 @@ def action_checkbox(self, obj):
"""
A list_display column containing a checkbox widget.
"""
- return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_unicode(obj.pk))
+ return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_text(obj.pk))
action_checkbox.short_description = mark_safe('<input type="checkbox" id="action-toggle" />')
action_checkbox.allow_tags = True
@@ -674,17 +674,17 @@ def construct_change_message(self, request, form, formsets):
for formset in formsets:
for added_object in formset.new_objects:
change_message.append(_('Added %(name)s "%(object)s".')
- % {'name': force_unicode(added_object._meta.verbose_name),
- 'object': force_unicode(added_object)})
+ % {'name': force_text(added_object._meta.verbose_name),
+ 'object': force_text(added_object)})
for changed_object, changed_fields in formset.changed_objects:
change_message.append(_('Changed %(list)s for %(name)s "%(object)s".')
% {'list': get_text_list(changed_fields, _('and')),
- 'name': force_unicode(changed_object._meta.verbose_name),
- 'object': force_unicode(changed_object)})
+ 'name': force_text(changed_object._meta.verbose_name),
+ 'object': force_text(changed_object)})
for deleted_object in formset.deleted_objects:
change_message.append(_('Deleted %(name)s "%(object)s".')
- % {'name': force_unicode(deleted_object._meta.verbose_name),
- 'object': force_unicode(deleted_object)})
+ % {'name': force_text(deleted_object._meta.verbose_name),
+ 'object': force_text(deleted_object)})
change_message = ' '.join(change_message)
return change_message or _('No fields changed.')
@@ -769,7 +769,7 @@ def response_add(self, request, obj, post_url_continue='../%s/'):
opts = obj._meta
pk_value = obj._get_pk_val()
- msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}
+ msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_text(opts.verbose_name), 'obj': force_text(obj)}
# Here, we distinguish between different save types by checking for
# the presence of keys in request.POST.
if "_continue" in request.POST:
@@ -782,10 +782,10 @@ def response_add(self, request, obj, post_url_continue='../%s/'):
return HttpResponse(
'<!DOCTYPE html><html><head><title></title></head><body>'
'<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script></body></html>' % \
- # escape() calls force_unicode.
+ # escape() calls force_text.
(escape(pk_value), escapejs(obj)))
elif "_addanother" in request.POST:
- self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
+ self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_text(opts.verbose_name)))
return HttpResponseRedirect(request.path)
else:
self.message_user(request, msg)
@@ -819,7 +819,7 @@ def response_change(self, request, obj):
pk_value = obj._get_pk_val()
- msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(verbose_name), 'obj': force_unicode(obj)}
+ msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_text(verbose_name), 'obj': force_text(obj)}
if "_continue" in request.POST:
self.message_user(request, msg + ' ' + _("You may edit it again below."))
if "_popup" in request.REQUEST:
@@ -827,14 +827,14 @@ def response_change(self, request, obj):
else:
return HttpResponseRedirect(request.path)
elif "_saveasnew" in request.POST:
- msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_unicode(verbose_name), 'obj': obj}
+ msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_text(verbose_name), 'obj': obj}
self.message_user(request, msg)
return HttpResponseRedirect(reverse('admin:%s_%s_change' %
(opts.app_label, module_name),
args=(pk_value,),
current_app=self.admin_site.name))
elif "_addanother" in request.POST:
- self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(verbose_name)))
+ self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_text(verbose_name)))
return HttpResponseRedirect(reverse('admin:%s_%s_add' %
(opts.app_label, module_name),
current_app=self.admin_site.name))
@@ -995,7 +995,7 @@ def add_view(self, request, form_url='', extra_context=None):
media = media + inline_admin_formset.media
context = {
- 'title': _('Add %s') % force_unicode(opts.verbose_name),
+ 'title': _('Add %s') % force_text(opts.verbose_name),
'adminform': adminForm,
'is_popup': "_popup" in request.REQUEST,
'media': media,
@@ -1019,7 +1019,7 @@ def change_view(self, request, object_id, form_url='', extra_context=None):
raise PermissionDenied
if obj is None:
- raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})
+ raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)})
if request.method == 'POST' and "_saveasnew" in request.POST:
return self.add_view(request, form_url=reverse('admin:%s_%s_add' %
@@ -1085,7 +1085,7 @@ def change_view(self, request, object_id, form_url='', extra_context=None):
media = media + inline_admin_formset.media
context = {
- 'title': _('Change %s') % force_unicode(opts.verbose_name),
+ 'title': _('Change %s') % force_text(opts.verbose_name),
'adminform': adminForm,
'object_id': object_id,
'original': obj,
@@ -1194,14 +1194,14 @@ def changelist_view(self, request, extra_context=None):
if changecount:
if changecount == 1:
- name = force_unicode(opts.verbose_name)
+ name = force_text(opts.verbose_name)
else:
- name = force_unicode(opts.verbose_name_plural)
+ name = force_text(opts.verbose_name_plural)
msg = ungettext("%(count)s %(name)s was changed successfully.",
"%(count)s %(name)s were changed successfully.",
changecount) % {'count': changecount,
'name': name,
- 'obj': force_unicode(obj)}
+ 'obj': force_text(obj)}
self.message_user(request, msg)
return HttpResponseRedirect(request.get_full_path())
@@ -1228,7 +1228,7 @@ def changelist_view(self, request, extra_context=None):
'All %(total_count)s selected', cl.result_count)
context = {
- 'module_name': force_unicode(opts.verbose_name_plural),
+ 'module_name': force_text(opts.verbose_name_plural),
'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
'selection_note_all': selection_note_all % {'total_count': cl.result_count},
'title': cl.title,
@@ -1263,7 +1263,7 @@ def delete_view(self, request, object_id, extra_context=None):
raise PermissionDenied
if obj is None:
- raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})
+ raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
@@ -1275,11 +1275,11 @@ def delete_view(self, request, object_id, extra_context=None):
if request.POST: # The user has already confirmed the deletion.
if perms_needed:
raise PermissionDenied
- obj_display = force_unicode(obj)
+ obj_display = force_text(obj)
self.log_deletion(request, obj, obj_display)
self.delete_model(request, obj)
- self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj_display)})
+ self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_text(opts.verbose_name), 'obj': force_text(obj_display)})
if not self.has_change_permission(request, None):
return HttpResponseRedirect(reverse('admin:index',
@@ -1288,7 +1288,7 @@ def delete_view(self, request, object_id, extra_context=None):
(opts.app_label, opts.module_name),
current_app=self.admin_site.name))
- object_name = force_unicode(opts.verbose_name)
+ object_name = force_text(opts.verbose_name)
if perms_needed or protected:
title = _("Cannot delete %(name)s") % {"name": object_name}
@@ -1326,9 +1326,9 @@ def history_view(self, request, object_id, extra_context=None):
# If no history was found, see whether this object even exists.
obj = get_object_or_404(model, pk=unquote(object_id))
context = {
- 'title': _('Change history: %s') % force_unicode(obj),
+ 'title': _('Change history: %s') % force_text(obj),
'action_list': action_list,
- 'module_name': capfirst(force_unicode(opts.verbose_name_plural)),
+ 'module_name': capfirst(force_text(opts.verbose_name_plural)),
'object': obj,
'app_label': app_label,
'opts': opts,
View
12 django/contrib/admin/templatetags/admin_list.py
@@ -15,7 +15,7 @@
from django.utils import six
from django.utils.text import capfirst
from django.utils.translation import ugettext as _
-from django.utils.encoding import smart_unicode, force_unicode
+from django.utils.encoding import smart_text, force_text
from django.template import Library
from django.template.loader import get_template
from django.template.context import Context
@@ -210,7 +210,7 @@ def items_for_result(cl, result, form):
result_repr = display_for_field(value, f)
if isinstance(f, (models.DateField, models.TimeField, models.ForeignKey)):
row_class = mark_safe(' class="nowrap"')
- if force_unicode(result_repr) == '':
+ if force_text(result_repr) == '':
result_repr = mark_safe('&nbsp;')
# If list_display_links not defined, add the link tag to the first field
if (first and not cl.list_display_links) or field_name in cl.list_display_links:
@@ -224,7 +224,7 @@ def items_for_result(cl, result, form):
else:
attr = pk
value = result.serializable_value(attr)
- result_id = repr(force_unicode(value))[1:]
+ result_id = repr(force_text(value))[1:]
yield format_html('<{0}{1}><a href="{2}"{3}>{4}</a></{5}>',
table_tag,
row_class,
@@ -241,10 +241,10 @@ def items_for_result(cl, result, form):
field_name == cl.model._meta.pk.name and
form[cl.model._meta.pk.name].is_hidden)):
bf = form[field_name]
- result_repr = mark_safe(force_unicode(bf.errors) + force_unicode(bf))
+ result_repr = mark_safe(force_text(bf.errors) + force_text(bf))
yield format_html('<td{0}>{1}</td>', row_class, result_repr)
if form and not form[cl.model._meta.pk.name].is_hidden:
- yield format_html('<td>{0}</td>', force_unicode(form[cl.model._meta.pk.name]))
+ yield format_html('<td>{0}</td>', force_text(form[cl.model._meta.pk.name]))
class ResultList(list):
# Wrapper class used to return items in a list_editable
@@ -267,7 +267,7 @@ def result_hidden_fields(cl):
if cl.formset:
for res, form in zip(cl.result_list, cl.formset.forms):
if form[cl.model._meta.pk.name].is_hidden:
- yield mark_safe(force_unicode(form[cl.model._meta.pk.name]))
+ yield mark_safe(force_text(form[cl.model._meta.pk.name]))
@register.inclusion_tag("admin/change_list_results.html")
def result_list(cl):
View
18 django/contrib/admin/util.py
@@ -12,7 +12,7 @@
from django.utils.html import format_html
from django.utils.text import capfirst
from django.utils import timezone
-from django.utils.encoding import force_unicode, smart_unicode, smart_str
+from django.utils.encoding import force_text, smart_text, smart_bytes
from django.utils import six
from django.utils.translation import ungettext
from django.core.urlresolvers import reverse
@@ -132,7 +132,7 @@ def format_callback(obj):
# Don't display link to edit, because it either has no
# admin or is edited inline.
return '%s: %s' % (capfirst(opts.verbose_name),
- force_unicode(obj))
+ force_text(obj))
to_delete = collector.nested(format_callback)
@@ -207,8 +207,8 @@ def model_format_dict(obj):
else:
opts = obj
return {
- 'verbose_name': force_unicode(opts.verbose_name),
- 'verbose_name_plural': force_unicode(opts.verbose_name_plural)
+ 'verbose_name': force_text(opts.verbose_name),
+ 'verbose_name_plural': force_text(opts.verbose_name_plural)
}
@@ -274,10 +274,10 @@ def label_for_field(name, model, model_admin=None, return_attr=False):
label = field.verbose_name
except models.FieldDoesNotExist:
if name == "__unicode__":
- label = force_unicode(model._meta.verbose_name)
+ label = force_text(model._meta.verbose_name)
attr = six.text_type
elif name == "__str__":
- label = smart_str(model._meta.verbose_name)
+ label = smart_bytes(model._meta.verbose_name)
attr = bytes
else:
if callable(name):
@@ -311,7 +311,7 @@ def help_text_for_field(name, model):
help_text = model._meta.get_field_by_name(name)[0].help_text
except models.FieldDoesNotExist:
help_text = ""
- return smart_unicode(help_text)
+ return smart_text(help_text)
def display_for_field(value, field):
@@ -335,7 +335,7 @@ def display_for_field(value, field):
elif isinstance(field, models.FloatField):
return formats.number_format(value)
else:
- return smart_unicode(value)
+ return smart_text(value)
def display_for_value(value, boolean=False):
@@ -353,7 +353,7 @@ def display_for_value(value, boolean=False):
elif isinstance(value, six.integer_types + (decimal.Decimal, float)):
return formats.number_format(value)
else:
- return smart_unicode(value)
+ return smart_text(value)
class NotRelationField(Exception):
View
6 django/contrib/admin/views/main.py
@@ -6,7 +6,7 @@
from django.db import models
from django.db.models.fields import FieldDoesNotExist
from django.utils.datastructures import SortedDict
-from django.utils.encoding import force_unicode, smart_str
+from django.utils.encoding import force_text, smart_bytes
from django.utils.translation import ugettext, ugettext_lazy
from django.utils.http import urlencode
@@ -75,7 +75,7 @@ def __init__(self, request, model, list_display, list_display_links,
title = ugettext('Select %s')
else:
title = ugettext('Select %s to change')
- self.title = title % force_unicode(self.opts.verbose_name)
+ self.title = title % force_text(self.opts.verbose_name)
self.pk_attname = self.lookup_opts.pk.attname
def get_filters(self, request):
@@ -94,7 +94,7 @@ def get_filters(self, request):
# 'key' will be used as a keyword argument later, so Python
# requires it to be a string.
del lookup_params[key]
- lookup_params[smart_str(key)] = value
+ lookup_params[smart_bytes(key)] = value
if not self.model_admin.lookup_allowed(key, value):
raise SuspiciousOperation("Filtering by %s not allowed" % key)
View
8 django/contrib/admin/widgets.py
@@ -14,7 +14,7 @@
from django.utils.text import Truncator
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
-from django.utils.encoding import force_unicode
+from django.utils.encoding import force_text
from django.utils import six
@@ -96,7 +96,7 @@ def render(self):
return format_html('<ul{0}>\n{1}\n</ul>',
flatatt(self.attrs),
format_html_join('\n', '<li>{0}</li>',
- ((force_unicode(w),) for w in self)))
+ ((force_text(w),) for w in self)))
class AdminRadioSelect(forms.RadioSelect):
renderer = AdminRadioFieldRenderer
@@ -197,7 +197,7 @@ def render(self, name, value, attrs=None):
# The related object is registered with the same AdminSite
attrs['class'] = 'vManyToManyRawIdAdminField'
if value:
- value = ','.join([force_unicode(v) for v in value])
+ value = ','.join([force_text(v) for v in value])
else:
value = ''
return super(ManyToManyRawIdWidget, self).render(name, value, attrs)
@@ -221,7 +221,7 @@ def _has_changed(self, initial, data):
if len(initial) != len(data):
return True
for pk1, pk2 in zip(initial, data):
- if force_unicode(pk1) != force_unicode(pk2):
+ if force_text(pk1) != force_text(pk2):
return True
return False
View
4 django/contrib/admindocs/utils.py
@@ -6,7 +6,7 @@
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
-from django.utils.encoding import smart_str
+from django.utils.encoding import smart_bytes
try:
import docutils.core
import docutils.nodes
@@ -66,7 +66,7 @@ def parse_rst(text, default_reference_context, thing_being_parsed=None):
"link_base" : reverse('django-admindocs-docroot').rstrip('/')
}
if thing_being_parsed:
- thing_being_parsed = smart_str("<%s>" % thing_being_parsed)
+ thing_being_parsed = smart_bytes("<%s>" % thing_being_parsed)
parts = docutils.core.publish_parts(text, source_path=thing_being_parsed,
destination_path=None, writer_name='html',
settings_overrides=overrides)
View
8 django/contrib/auth/hashers.py
@@ -7,7 +7,7 @@
from django.test.signals import setting_changed
from django.utils import importlib
from django.utils.datastructures import SortedDict
-from django.utils.encoding import smart_str
+from django.utils.encoding import smart_bytes
from django.core.exceptions import ImproperlyConfigured
from django.utils.crypto import (
pbkdf2, constant_time_compare, get_random_string)
@@ -298,7 +298,7 @@ class SHA1PasswordHasher(BasePasswordHasher):
def encode(self, password, salt):
assert password
assert salt and '$' not in salt
- hash = hashlib.sha1(smart_str(salt + password)).hexdigest()
+ hash = hashlib.sha1(smart_bytes(salt + password)).hexdigest()
return "%s$%s$%s" % (self.algorithm, salt, hash)
def verify(self, password, encoded):
@@ -326,7 +326,7 @@ class MD5PasswordHasher(BasePasswordHasher):
def encode(self, password, salt):
assert password
assert salt and '$' not in salt
- hash = hashlib.md5(smart_str(salt + password)).hexdigest()
+ hash = hashlib.md5(smart_bytes(salt + password)).hexdigest()
return "%s$%s$%s" % (self.algorithm, salt, hash)
def verify(self, password, encoded):
@@ -360,7 +360,7 @@ def salt(self):
return ''
def encode(self, password, salt):
- return hashlib.md5(smart_str(password)).hexdigest()
+ return hashlib.md5(smart_bytes(password)).hexdigest()
def verify(self, password, encoded):
encoded_2 = self.encode(password, '')
View
28 django/contrib/auth/tests/forms.py
@@ -8,7 +8,7 @@
from django.forms.fields import Field, EmailField
from django.test import TestCase
from django.test.utils import override_settings
-from django.utils.encoding import force_unicode
+from django.utils.encoding import force_text
from django.utils import six
from django.utils import translation
from django.utils.translation import ugettext as _
@@ -28,7 +28,7 @@ def test_user_already_exists(self):
form = UserCreationForm(data)
self.assertFalse(form.is_valid())
self.assertEqual(form["username"].errors,
- [force_unicode(form.error_messages['duplicate_username'])])
+ [force_text(form.error_messages['duplicate_username'])])
def test_invalid_data(self):
data = {
@@ -39,7 +39,7 @@ def test_invalid_data(self):
form = UserCreationForm(data)
self.assertFalse(form.is_valid())
self.assertEqual(form["username"].errors,
- [force_unicode(form.fields['username'].error_messages['invalid'])])
+ [force_text(form.fields['username'].error_messages['invalid'])])
def test_password_verification(self):
# The verification password is incorrect.
@@ -51,13 +51,13 @@ def test_password_verification(self):
form = UserCreationForm(data)
self.assertFalse(form.is_valid())
self.assertEqual(form["password2"].errors,
- [force_unicode(form.error_messages['password_mismatch'])])
+ [force_text(form.error_messages['password_mismatch'])])
def test_both_passwords(self):
# One (or both) passwords weren't given
data = {'username': 'jsmith'}
form = UserCreationForm(data)
- required_error = [force_unicode(Field.default_error_messages['required'])]
+ required_error = [force_text(Field.default_error_messages['required'])]
self.assertFalse(form.is_valid())
self.assertEqual(form['password1'].errors, required_error)
self.assertEqual(form['password2'].errors, required_error)
@@ -96,7 +96,7 @@ def test_invalid_username(self):
form = AuthenticationForm(None, data)
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(),
- [force_unicode(form.error_messages['invalid_login'])])
+ [force_text(form.error_messages['invalid_login'])])
def test_inactive_user(self):
# The user is inactive.
@@ -107,7 +107,7 @@ def test_inactive_user(self):
form = AuthenticationForm(None, data)
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(),
- [force_unicode(form.error_messages['inactive'])])
+ [force_text(form.error_messages['inactive'])])
def test_inactive_user_i18n(self):
with self.settings(USE_I18N=True):
@@ -120,7 +120,7 @@ def test_inactive_user_i18n(self):
form = AuthenticationForm(None, data)
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(),
- [force_unicode(form.error_messages['inactive'])])
+ [force_text(form.error_messages['inactive'])])
def test_success(self):
# The success case
@@ -148,7 +148,7 @@ def test_password_verification(self):
form = SetPasswordForm(user, data)
self.assertFalse(form.is_valid())
self.assertEqual(form["new_password2"].errors,
- [force_unicode(form.error_messages['password_mismatch'])])
+ [force_text(form.error_messages['password_mismatch'])])
def test_success(self):
user = User.objects.get(username='testclient')
@@ -175,7 +175,7 @@ def test_incorrect_password(self):
form = PasswordChangeForm(user, data)
self.assertFalse(form.is_valid())
self.assertEqual(form["old_password"].errors,
- [force_unicode(form.error_messages['password_incorrect'])])
+ [force_text(form.error_messages['password_incorrect'])])
def test_password_verification(self):
# The two new passwords do not match.
@@ -188,7 +188,7 @@ def test_password_verification(self):
form = PasswordChangeForm(user, data)
self.assertFalse(form.is_valid())
self.assertEqual(form["new_password2"].errors,
- [force_unicode(form.error_messages['password_mismatch'])])
+ [force_text(form.error_messages['password_mismatch'])])
def test_success(self):
# The success case.
@@ -219,7 +219,7 @@ def test_username_validity(self):
form = UserChangeForm(data, instance=user)
self.assertFalse(form.is_valid())
self.assertEqual(form['username'].errors,
- [force_unicode(form.fields['username'].error_messages['invalid'])])
+ [force_text(form.fields['username'].error_messages['invalid'])])
def test_bug_14242(self):
# A regression test, introduce by adding an optimization for the
@@ -274,7 +274,7 @@ def test_invalid_email(self):
form = PasswordResetForm(data)
self.assertFalse(form.is_valid())
self.assertEqual(form['email'].errors,
- [force_unicode(EmailField.default_error_messages['invalid'])])
+ [force_text(EmailField.default_error_messages['invalid'])])
def test_nonexistant_email(self):
# Test nonexistant email address
@@ -282,7 +282,7 @@ def test_nonexistant_email(self):
form = PasswordResetForm(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors,
- {'email': [force_unicode(form.error_messages['unknown'])]})
+ {'email': [force_text(form.error_messages['unknown'])]})
def test_cleaned_data(self):
# Regression test
View
4 django/contrib/auth/tests/views.py
@@ -7,7 +7,7 @@
from django.core import mail
from django.core.urlresolvers import reverse, NoReverseMatch
from django.http import QueryDict
-from django.utils.encoding import force_unicode
+from django.utils.encoding import force_text
from django.utils.html import escape
from django.utils.http import urlquote
from django.test import TestCase
@@ -46,7 +46,7 @@ def login(self, password='password'):
self.assertTrue(SESSION_KEY in self.client.session)
def assertContainsEscaped(self, response, text, **kwargs):
- return self.assertContains(response, escape(force_unicode(text)), **kwargs)
+ return self.assertContains(response, escape(force_text(text)), **kwargs)
class AuthViewNamedURLTests(AuthViewsTestCase):
View
4 django/contrib/comments/forms.py
@@ -5,7 +5,7 @@
from django.contrib.contenttypes.models import ContentType
from django.contrib.comments.models import Comment
from django.utils.crypto import salted_hmac, constant_time_compare
-from django.utils.encoding import force_unicode
+from django.utils.encoding import force_text
from django.utils.text import get_text_list
from django.utils import timezone
from django.utils.translation import ungettext, ugettext, ugettext_lazy as _
@@ -133,7 +133,7 @@ def get_comment_create_data(self):
"""
return dict(
content_type = ContentType.objects.get_for_model(self.target_object),
- object_pk = force_unicode(self.target_object._get_pk_val()),
+ object_pk = force_text(self.target_object._get_pk_val()),
user_name = self.cleaned_data["name"],
user_email = self.cleaned_data["email"],
user_url = self.cleaned_data["url"],
View
4 django/contrib/comments/managers.py
@@ -1,6 +1,6 @@
from django.db import models
from django.contrib.contenttypes.models import ContentType
-from django.utils.encoding import force_unicode
+from django.utils.encoding import force_text
class CommentManager(models.Manager):
@@ -18,5 +18,5 @@ def for_model(self, model):
ct = ContentType.objects.get_for_model(model)
qs = self.get_query_set().filter(content_type=ct)
if isinstance(model, models.Model):
- qs = qs.filter(object_pk=force_unicode(model._get_pk_val()))
+ qs = qs.filter(object_pk=force_text(model._get_pk_val()))
return qs
View
4 django/contrib/comments/templatetags/comments.py
@@ -3,7 +3,7 @@
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib import comments
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
register = template.Library()
@@ -75,7 +75,7 @@ def get_query_set(self, context):
qs = self.comment_model.objects.filter(
content_type = ctype,
- object_pk = smart_unicode(object_pk),
+ object_pk = smart_text(object_pk),
site__pk = settings.SITE_ID,
)
View
4 django/contrib/contenttypes/generic.py
@@ -17,7 +17,7 @@
from django.forms.models import BaseModelFormSet, modelformset_factory, save_instance
from django.contrib.admin.options import InlineModelAdmin, flatten_fieldsets
from django.contrib.contenttypes.models import ContentType
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
class GenericForeignKey(object):
"""
@@ -169,7 +169,7 @@ def get_choices_default(self):
def value_to_string(self, obj):
qs = getattr(obj, self.name).all()
- return smart_unicode([instance._get_pk_val() for instance in qs])
+ return smart_text([instance._get_pk_val() for instance in qs])
def m2m_db_table(self):
return self.rel.to._meta.db_table
View
4 django/contrib/contenttypes/management.py
@@ -1,6 +1,6 @@
from django.contrib.contenttypes.models import ContentType
from django.db.models import get_apps, get_models, signals
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils import six
def update_contenttypes(app, created_models, verbosity=2, **kwargs):
@@ -31,7 +31,7 @@ def update_contenttypes(app, created_models, verbosity=2, **kwargs):
cts = ContentType.objects.bulk_create([
ContentType(
- name=smart_unicode(model._meta.verbose_name_raw),
+ name=smart_text(model._meta.verbose_name_raw),
app_label=app_label,
model=model_name,
)
View
10 django/contrib/contenttypes/models.py
@@ -1,6 +1,6 @@
from django.db import models
from django.utils.translation import ugettext_lazy as _
-from django.utils.encoding import smart_unicode, force_unicode
+from django.utils.encoding import smart_text, force_text
class ContentTypeManager(models.Manager):
@@ -37,13 +37,13 @@ def get_for_model(self, model, for_concrete_model=True):
try:
ct = self._get_from_cache(opts)
except KeyError:
- # Load or create the ContentType entry. The smart_unicode() is
+ # Load or create the ContentType entry. The smart_text() is
# needed around opts.verbose_name_raw because name_raw might be a
# django.utils.functional.__proxy__ object.
ct, created = self.get_or_create(
app_label = opts.app_label,
model = opts.object_name.lower(),
- defaults = {'name': smart_unicode(opts.verbose_name_raw)},
+ defaults = {'name': smart_text(opts.verbose_name_raw)},
)
self._add_to_cache(self.db, ct)
@@ -86,7 +86,7 @@ def get_for_models(self, *models, **kwargs):
ct = self.create(
app_label=opts.app_label,
model=opts.object_name.lower(),
- name=smart_unicode(opts.verbose_name_raw),
+ name=smart_text(opts.verbose_name_raw),
)
self._add_to_cache(self.db, ct)
results[ct.model_class()] = ct
@@ -147,7 +147,7 @@ def __unicode__(self):
if not model or self.name != model._meta.verbose_name_raw:
return self.name
else:
- return force_unicode(model._meta.verbose_name)
+ return force_text(model._meta.verbose_name)
def model_class(self):
"Returns the Python model class for this type of content."
View
16 django/contrib/databrowse/datastructures.py
@@ -7,7 +7,7 @@
from django.db import models
from django.utils import formats
from django.utils.text import capfirst
-from django.utils.encoding import smart_unicode, smart_str, iri_to_uri
+from django.utils.encoding import smart_text, smart_bytes, iri_to_uri
from django.db.models.query import QuerySet
EMPTY_VALUE = '(None)'
@@ -22,7 +22,7 @@ def __init__(self, site, model):
self.verbose_name_plural = model._meta.verbose_name_plural
def __repr__(self):
- return '<EasyModel for %s>' % smart_str(self.model._meta.object_name)
+ return '<EasyModel for %s>' % smart_bytes(self.model._meta.object_name)
def model_databrowse(self):
"Returns the ModelDatabrowse class for this model."
@@ -61,7 +61,7 @@ def __init__(self, easy_model, field):
self.model, self.field = easy_model, field
def __repr__(self):
- return smart_str('<EasyField for %s.%s>' % (self.model.model._meta.object_name, self.field.name))
+ return smart_bytes('<EasyField for %s.%s>' % (self.model.model._meta.object_name, self.field.name))
def choices(self):
for value, label in self.field.choices:
@@ -79,7 +79,7 @@ def __init__(self, easy_model, field, value, label):
self.value, self.label = value, label
def __repr__(self):
- return smart_str('<EasyChoice for %s.%s>' % (self.model.model._meta.object_name, self.field.name))
+ return smart_bytes('<EasyChoice for %s.%s>' % (self.model.model._meta.object_name, self.field.name))
def url(self):
return '%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,10 +89,10 @@ def __init__(self, easy_model, instance):
self.model, self.instance = easy_model, instance
def __repr__(self):
- return smart_str('<EasyInstance for %s (%s)>' % (self.model.model._meta.object_name, self.instance._get_pk_val()))
+ return smart_bytes('<EasyInstance for %s (%s)>' % (self.model.model._meta.object_name, self.instance._get_pk_val()))
def __unicode__(self):
- val = smart_unicode(self.instance)
+ val = smart_text(self.instance)
if len(val) > DISPLAY_SIZE:
return val[:DISPLAY_SIZE] + '...'
return val
@@ -136,7 +136,7 @@ def __init__(self, easy_model, instance, field):
self.raw_value = getattr(instance.instance, field.name)
def __repr__(self):
- return smart_str('<EasyInstanceField for %s.%s>' % (self.model.model._meta.object_name, self.field.name))
+ return smart_bytes('<EasyInstanceField for %s.%s>' % (self.model.model._meta.object_name, self.field.name))
def values(self):
"""
@@ -185,7 +185,7 @@ def urls(self):
if value is None:
continue
url = '%s%s/%s/objects/%s/' % (self.model.site.root_url, m.model._meta.app_label, m.model._meta.module_name, iri_to_uri(value._get_pk_val()))
- lst.append((smart_unicode(value), url))
+ lst.append((smart_text(value), url))
else:
lst = [(value, None) for value in self.values()]
elif self.field.choices:
View
4 django/contrib/databrowse/plugins/calendars.py
@@ -7,7 +7,7 @@
from django.shortcuts import render_to_response
from django.utils.html import format_html, format_html_join
from django.utils.text import capfirst
-from django.utils.encoding import force_unicode
+from django.utils.encoding import force_text
from django.views.generic import dates
from django.utils import datetime_safe
@@ -66,7 +66,7 @@ def model_index_html(self, request, model, site):
return ''
return format_html('<p class="filter"><strong>View calendar by:</strong> {0}</p>',
format_html_join(', ', '<a href="calendars/{0}/">{1}</a>',
- ((f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values())))
+ ((f.name, force_text(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):
View
4 django/contrib/databrowse/plugins/fieldchoices.py
@@ -8,7 +8,7 @@
from django.utils.html import format_html, format_html_join
from django.utils.http import urlquote
from django.utils.text import capfirst
-from django.utils.encoding import force_unicode
+from django.utils.encoding import force_text
class FieldChoicePlugin(DatabrowsePlugin):
@@ -35,7 +35,7 @@ def model_index_html(self, request, model, site):
return ''
return format_html('<p class="filter"><strong>View by:</strong> {0}</p>',
format_html_join(', ', '<a href="fields/{0}/">{1}</a>',
- ((f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values())))
+ ((f.name, force_text(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():
View
4 django/contrib/formtools/wizard/storage/base.py
@@ -1,6 +1,6 @@
from django.core.files.uploadedfile import UploadedFile
from django.utils.datastructures import MultiValueDict
-from django.utils.encoding import smart_str
+from django.utils.encoding import smart_bytes
from django.utils.functional import lazy_property
from django.utils import six
@@ -74,7 +74,7 @@ def get_step_files(self, step):
files = {}
for field, field_dict in six.iteritems(wizard_files):
- field_dict = dict((smart_str(k), v)
+ field_dict = dict((smart_bytes(k), v)
for k, v in six.iteritems(field_dict))
tmp_name = field_dict.pop('tmp_name')
files[field] = UploadedFile(
View
4 django/contrib/gis/sitemaps/views.py
@@ -8,7 +8,7 @@
from django.contrib.gis.db.models.fields import GeometryField
from django.db import connections, DEFAULT_DB_ALIAS
from django.db.models import get_model
-from django.utils.encoding import smart_str
+from django.utils.encoding import smart_bytes
from django.utils import six
from django.utils.translation import ugettext as _
@@ -61,7 +61,7 @@ def sitemap(request, sitemaps, section=None):
raise Http404(_("Page %s empty") % page)
except PageNotAnInteger:
raise Http404(_("No page '%s'") % page)
- xml = smart_str(loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls}))
+ xml = smart_bytes(loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls}))
return HttpResponse(xml, content_type='application/xml')
def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB_ALIAS):
View
4 django/contrib/humanize/templatetags/humanize.py
@@ -5,7 +5,7 @@
from django import template
from django.conf import settings
from django.template import defaultfilters
-from django.utils.encoding import force_unicode
+from django.utils.encoding import force_text
from django.utils.formats import number_format
from django.utils.translation import pgettext, ungettext, ugettext as _
from django.utils.timezone import is_aware, utc
@@ -41,7 +41,7 @@ def intcomma(value, use_l10n=True):
return intcomma(value, False)
else:
return number_format(value, force_grouping=True)
- orig = force_unicode(value)
+ orig = force_text(value)
new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig)
if orig == new:
return new
View
4 django/contrib/localflavor/au/forms.py
@@ -10,7 +10,7 @@
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
@@ -44,7 +44,7 @@ def clean(self, value):
super(AUPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return ''
- value = re.sub('(\(|\)|\s+|-)', '', smart_unicode(value))
+ value = re.sub('(\(|\)|\s+|-)', '', smart_text(value))
phone_match = PHONE_DIGITS_RE.search(value)
if phone_match:
return '%s' % phone_match.group(1)
View
8 django/contrib/localflavor/br/forms.py
@@ -11,7 +11,7 @@
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, CharField, Select
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
@@ -35,7 +35,7 @@ def clean(self, value):
super(BRPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return ''
- value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
+ value = re.sub('(\(|\)|\s+)', '', smart_text(value))
m = phone_digits_re.search(value)
if m:
return '%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
@@ -68,10 +68,10 @@ def clean(self, value):
value = super(BRStateChoiceField, self).clean(value)
if value in EMPTY_VALUES:
value = ''
- value = smart_unicode(value)
+ value = smart_text(value)
if value == '':
return value
- valid_values = set([smart_unicode(k) for k, v in self.widget.choices])
+ valid_values = set([smart_text(k) for k, v in self.widget.choices])
if value not in valid_values:
raise ValidationError(self.error_messages['invalid'])
return value
View
4 django/contrib/localflavor/ca/forms.py
@@ -9,7 +9,7 @@
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, CharField, Select
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
@@ -53,7 +53,7 @@ def clean(self, value):
super(CAPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return ''
- value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
+ value = re.sub('(\(|\)|\s+)', '', smart_text(value))
m = phone_digits_re.search(value)
if m:
return '%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
View
4 django/contrib/localflavor/ch/forms.py
@@ -10,7 +10,7 @@
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
@@ -41,7 +41,7 @@ def clean(self, value):
super(CHPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return ''
- value = re.sub('(\.|\s|/|-)', '', smart_unicode(value))
+ value = re.sub('(\.|\s|/|-)', '', smart_text(value))
m = phone_digits_re.search(value)
if m:
return '%s %s %s %s' % (value[0:3], value[3:6], value[6:8], value[8:10])
View
4 django/contrib/localflavor/cl/forms.py
@@ -8,7 +8,7 @@
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 django.utils.encoding import smart_text
from .cl_regions import REGION_CHOICES
@@ -75,7 +75,7 @@ def _canonify(self, rut):
Turns the RUT into one normalized format. Returns a (rut, verifier)
tuple.
"""
- rut = smart_unicode(rut).replace(' ', '').replace('.', '').replace('-', '')
+ rut = smart_text(rut).replace(' ', '').replace('.', '').replace('-', '')
return rut[:-1], rut[-1].upper()
def _format(self, code, verifier=None):
View
4 django/contrib/localflavor/fr/forms.py
@@ -9,7 +9,7 @@
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import CharField, RegexField, Select
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
@@ -43,7 +43,7 @@ def clean(self, value):
super(FRPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return ''
- value = re.sub('(\.|\s)', '', smart_unicode(value))
+ value = re.sub('(\.|\s)', '', smart_text(value))
m = phone_digits_re.search(value)
if m:
return '%s %s %s %s %s' % (value[0:2], value[2:4], value[4:6], value[6:8], value[8:10])
View
4 django/contrib/localflavor/hk/forms.py
@@ -8,7 +8,7 @@
from django.core.validators import EMPTY_VALUES
from django.forms import CharField
from django.forms import ValidationError
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
@@ -53,7 +53,7 @@ def clean(self, value):
if value in EMPTY_VALUES:
return ''
- value = re.sub('(\(|\)|\s+|\+)', '', smart_unicode(value))
+ value = re.sub('(\(|\)|\s+|\+)', '', smart_text(value))
m = hk_phone_digits_re.search(value)
if not m:
raise ValidationError(self.error_messages['invalid'])
View
6 django/contrib/localflavor/hr/forms.py
@@ -12,7 +12,7 @@
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, Select, RegexField
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
@@ -159,7 +159,7 @@ def clean(self, value):
if value in EMPTY_VALUES:
return ''
- value = re.sub(r'[\s\-]+', '', smart_unicode(value.strip())).upper()
+ value = re.sub(r'[\s\-]+', '', smart_text(value.strip())).upper()
matches = plate_re.search(value)
if matches is None:
@@ -225,7 +225,7 @@ def clean(self, value):
if value in EMPTY_VALUES:
return ''
- value = re.sub(r'[\-\s\(\)]', '', smart_unicode(value))
+ value = re.sub(r'[\-\s\(\)]', '', smart_text(value))
matches = phone_re.search(value)
if matches is None:
View
10 django/contrib/localflavor/id/forms.py
@@ -11,7 +11,7 @@
from django.forms import ValidationError
from django.forms.fields import Field, Select
from django.utils.translation import ugettext_lazy as _
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
postcode_re = re.compile(r'^[1-9]\d{4}$')
@@ -77,10 +77,10 @@ def clean(self, value):
if value in EMPTY_VALUES:
return ''
- phone_number = re.sub(r'[\-\s\(\)]', '', smart_unicode(value))
+ phone_number = re.sub(r'[\-\s\(\)]', '', smart_text(value))
if phone_re.search(phone_number):
- return smart_unicode(value)
+ return smart_text(value)
raise ValidationError(self.error_messages['invalid'])
@@ -120,7 +120,7 @@ def clean(self, value):
return ''
plate_number = re.sub(r'\s+', ' ',
- smart_unicode(value.strip())).upper()
+ smart_text(value.strip())).upper()
matches = plate_re.search(plate_number)
if matches is None:
@@ -181,7 +181,7 @@ def clean(self, value):
if value in EMPTY_VALUES:
return ''
- value = re.sub(r'[\s.]', '', smart_unicode(value))
+ value = re.sub(r'[\s.]', '', smart_text(value))
if not nik_re.search(value):
raise ValidationError(self.error_messages['invalid'])
View
6 django/contrib/localflavor/in_/forms.py
@@ -10,7 +10,7 @@
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, CharField, Select
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
@@ -74,7 +74,7 @@ def clean(self, value):
pass
else:
try:
- return smart_unicode(STATES_NORMALIZED[value.strip().lower()])
+ return smart_text(STATES_NORMALIZED[value.strip().lower()])
except KeyError:
pass
raise ValidationError(self.error_messages['invalid'])
@@ -107,7 +107,7 @@ def clean(self, value):
super(INPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return ''
- value = smart_unicode(value)
+ value = smart_text(value)
m = phone_digits_re.match(value)
if m:
return '%s' % (value)
View
4 django/contrib/localflavor/is_/forms.py
@@ -9,7 +9,7 @@
from django.forms import ValidationError
from django.forms.fields import RegexField
from django.forms.widgets import Select
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
@@ -58,7 +58,7 @@ def _format(self, value):
Takes in the value in canonical form and returns it in the common
display format.
"""
- return smart_unicode(value[:6]+'-'+value[6:])
+ return smart_text(value[:6]+'-'+value[6:])
class ISPhoneNumberField(RegexField):
"""
View
4 django/contrib/localflavor/it/forms.py
@@ -13,7 +13,7 @@
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select
from django.utils.translation import ugettext_lazy as _
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
class ITZipCodeField(RegexField):
@@ -85,4 +85,4 @@ def clean(self, value):
check_digit = vat_number_check_digit(vat_number[0:10])
if not vat_number[10] == check_digit:
raise ValidationError(self.error_messages['invalid'])
- return smart_unicode(vat_number)
+ return smart_text(vat_number)
View
6 django/contrib/localflavor/it/util.py
@@ -1,4 +1,4 @@
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
def ssn_check_digit(value):
"Calculate Italian social security number check digit."
@@ -34,11 +34,11 @@ def ssn_check_digit(value):
def vat_number_check_digit(vat_number):
"Calculate Italian VAT number check digit."
- normalized_vat_number = smart_unicode(vat_number).zfill(10)
+ normalized_vat_number = smart_text(vat_number).zfill(10)
total = 0
for i in range(0, 10, 2):
total += int(normalized_vat_number[i])
for i in range(1, 11, 2):
quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, 10)
total += quotient + remainder
- return smart_unicode((10 - total % 10) % 10)
+ return smart_text((10 - total % 10) % 10)
View
4 django/contrib/localflavor/nl/forms.py
@@ -10,7 +10,7 @@
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, Select
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
@@ -61,7 +61,7 @@ def clean(self, value):
if value in EMPTY_VALUES:
return ''
- phone_nr = re.sub('[\-\s\(\)]', '', smart_unicode(value))
+ phone_nr = re.sub('[\-\s\(\)]', '', smart_text(value))
if len(phone_nr) == 10 and numeric_re.search(phone_nr):
return value
View
6 django/contrib/localflavor/pt/forms.py
@@ -8,7 +8,7 @@
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
phone_digits_re = re.compile(r'^(\d{9}|(00|\+)\d*)$')
@@ -29,7 +29,7 @@ def clean(self,value):
return '%s-%s' % (cleaned[:4],cleaned[4:])
else:
return cleaned
-
+
class PTPhoneNumberField(Field):
"""
Validate local Portuguese phone number (including international ones)
@@ -43,7 +43,7 @@ def clean(self, value):
super(PTPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return ''
- value = re.sub('(\.|\s)', '', smart_unicode(value))
+ value = re.sub('(\.|\s)', '', smart_text(value))
m = phone_digits_re.search(value)
if m:
return '%s' % value
View
4 django/contrib/localflavor/tr/forms.py
@@ -10,7 +10,7 @@
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select, CharField
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
@@ -46,7 +46,7 @@ def clean(self, value):
super(TRPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return ''
- value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
+ value = re.sub('(\(|\)|\s+)', '', smart_text(value))
m = phone_digits_re.search(value)
if m:
return '%s%s' % (m.group(2), m.group(4))
View
4 django/contrib/localflavor/us/forms.py
@@ -9,7 +9,7 @@
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select, CharField
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.translation import ugettext_lazy as _
@@ -34,7 +34,7 @@ def clean(self, value):
super(USPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return ''
- value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
+ value = re.sub('(\(|\)|\s+)', '', smart_text(value))
m = phone_digits_re.search(value)
if m:
return '%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
View
20 django/contrib/markup/templatetags/markup.py
@@ -13,7 +13,7 @@
from django import template
from django.conf import settings
-from django.utils.encoding import smart_str, force_unicode
+from django.utils.encoding import smart_bytes, force_text
from django.utils.safestring import mark_safe
register = template.Library()
@@ -25,9 +25,9 @@ def textile(value):
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in 'textile' filter: The Python textile library isn't installed.")
- return force_unicode(value)
+ return force_text(value)
else:
- return mark_safe(force_unicode(textile.textile(smart_str(value), encoding='utf-8', output='utf-8')))
+ return mark_safe(force_text(textile.textile(smart_bytes(value), encoding='utf-8', output='utf-8')))
@register.filter(is_safe=True)
def markdown(value, arg=''):
@@ -52,23 +52,23 @@ def markdown(value, arg=''):
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in 'markdown' filter: The Python markdown library isn't installed.")
- return force_unicode(value)
+ return force_text(value)
else:
markdown_vers = getattr(markdown, "version_info", 0)
if markdown_vers < (2, 1):
if settings.DEBUG:
raise template.TemplateSyntaxError(
"Error in 'markdown' filter: Django does not support versions of the Python markdown library < 2.1.")
- return force_unicode(value)
+ return force_text(value)
else:
extensions = [e for e in arg.split(",") if e]
if extensions and extensions[0] == "safe":
extensions = extensions[1:]
return mark_safe(markdown.markdown(
- force_unicode(value), extensions, safe_mode=True, enable_attributes=False))
+ force_text(value), extensions, safe_mode=True, enable_attributes=False))
else:
return mark_safe(markdown.markdown(
- force_unicode(value), extensions, safe_mode=False))
+ force_text(value), extensions, safe_mode=False))
@register.filter(is_safe=True)
def restructuredtext(value):
@@ -77,8 +77,8 @@ def restructuredtext(value):
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in 'restructuredtext' filter: The Python docutils library isn't installed.")
- return force_unicode(value)
+ return force_text(value)
else:
docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {})
- parts = publish_parts(source=smart_str(value), writer_name="html4css1", settings_overrides=docutils_settings)
- return mark_safe(force_unicode(parts["fragment"]))
+ parts = publish_parts(source=smart_bytes(value), writer_name="html4css1", settings_overrides=docutils_settings)
+ return mark_safe(force_text(parts["fragment"]))
View
14 django/contrib/messages/storage/base.py
@@ -1,7 +1,7 @@
from __future__ import unicode_literals
from django.conf import settings
-from django.utils.encoding import force_unicode, StrAndUnicode
+from django.utils.encoding import force_text, StrAndUnicode
from django.contrib.messages import constants, utils
@@ -26,22 +26,22 @@ def _prepare(self):
and ``extra_tags`` to unicode in case they are lazy translations.
Known "safe" types (None, int, etc.) are not converted (see Django's
- ``force_unicode`` implementation for details).
+ ``force_text`` implementation for details).
"""
- self.message = force_unicode(self.message, strings_only=True)
- self.extra_tags = force_unicode(self.extra_tags, strings_only=True)
+ self.message = force_text(self.message, strings_only=True)
+ self.extra_tags = force_text(self.extra_tags, strings_only=True)
def __eq__(self, other):
return isinstance(other, Message) and self.level == other.level and \
self.message == other.message
def __unicode__(self):
- return force_unicode(self.message)
+ return force_text(self.message)
def _get_tags(self):
- label_tag = force_unicode(LEVEL_TAGS.get(self.level, ''),
+ label_tag = force_text(LEVEL_TAGS.get(self.level, ''),
strings_only=True)
- extra_tags = force_unicode(self.extra_tags, strings_only=True)
+ extra_tags = force_text(self.extra_tags, strings_only=True)
if extra_tags and label_tag:
return ' '.join([extra_tags, label_tag])
elif extra_tags:
View
4 django/contrib/sessions/backends/db.py
@@ -1,7 +1,7 @@
from django.contrib.sessions.backends.base import SessionBase, CreateError
from django.core.exceptions import SuspiciousOperation
from django.db import IntegrityError, transaction, router
-from django.utils.encoding import force_unicode
+from django.utils.encoding import force_text
from django.utils import timezone
@@ -18,7 +18,7 @@ def load(self):
session_key = self.session_key,
expire_date__gt=timezone.now()
)
- return self.decode(force_unicode(s.session_data))
+ return self.decode(force_text(s.session_data))
except (Session.DoesNotExist, SuspiciousOperation):
self.create()
return {}
View
6 django/contrib/staticfiles/management/commands/collectstatic.py
@@ -6,7 +6,7 @@
from django.core.files.storage import FileSystemStorage
from django.core.management.base import CommandError, NoArgsCommand
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_text
from django.utils.datastructures import SortedDict
from django.contrib.staticfiles import finders, storage
@@ -198,9 +198,9 @@ def clear_dir(self, path):
fpath = os.path.join(path, f)
if self.dry_run:
self.log("Pretending to delete '%s'" %
- smart_unicode(fpath), level=1)
+ smart_text(fpath), level=1)
else:
- self.log("Deleting '%s'" % smart_unicode(fpath), level=1)
+ self.log("Deleting '%s'" % smart_text(fpath), level=1)
self.storage.delete(fpath)
for d in dirs:
self.clear_dir(os.path.join(path, d))
View
6 django/contrib/staticfiles/management/commands/findstatic.py
@@ -3,7 +3,7 @@
import os
from optparse import make_option