Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge branch 'master' into schema-alteration

  • Loading branch information...
commit 184cf9ab798d5b25d855649ddb2ca580949778df 2 parents c4b2a32 + 7275576
@andrewgodwin andrewgodwin authored
Showing with 2,523 additions and 1,747 deletions.
  1. +1 −1  django/conf/__init__.py
  2. +1 −1  django/conf/locale/fi/formats.py
  3. +8 −7 django/conf/locale/gl/formats.py
  4. +2 −2 django/conf/urls/i18n.py
  5. +4 −4 django/contrib/admin/actions.py
  6. +4 −4 django/contrib/admin/filters.py
  7. +7 −7 django/contrib/admin/helpers.py
  8. +3 −3 django/contrib/admin/models.py
  9. +32 −32 django/contrib/admin/options.py
  10. +4 −3 django/contrib/admin/sites.py
  11. +8 −7 django/contrib/admin/templatetags/admin_list.py
  12. +9 −9 django/contrib/admin/util.py
  13. +3 −3 django/contrib/admin/views/main.py
  14. +4 −4 django/contrib/admin/widgets.py
  15. +2 −2 django/contrib/admindocs/utils.py
  16. +3 −2 django/contrib/admindocs/views.py
  17. +2 −1  django/contrib/auth/admin.py
  18. +2 −1  django/contrib/auth/context_processors.py
  19. +3 −3 django/contrib/auth/forms.py
  20. +6 −5 django/contrib/auth/hashers.py
  21. +3 −2 django/contrib/auth/management/__init__.py
  22. +3 −2 django/contrib/auth/management/commands/createsuperuser.py
  23. +17 −15 django/contrib/auth/tests/forms.py
  24. +2 −2 django/contrib/auth/tests/views.py
  25. +2 −2 django/contrib/comments/forms.py
  26. +2 −2 django/contrib/comments/managers.py
  27. +2 −2 django/contrib/comments/templatetags/comments.py
  28. +2 −2 django/contrib/contenttypes/generic.py
  29. +7 −5 django/contrib/contenttypes/management.py
  30. +5 −5 django/contrib/contenttypes/models.py
  31. +11 −13 django/contrib/databrowse/datastructures.py
  32. +3 −3 django/contrib/databrowse/plugins/calendars.py
  33. +3 −3 django/contrib/databrowse/plugins/fieldchoices.py
  34. +1 −1  django/contrib/formtools/tests/__init__.py
  35. +6 −5 django/contrib/formtools/wizard/storage/base.py
  36. +4 −4 django/contrib/formtools/wizard/views.py
  37. +3 −1 django/contrib/gis/db/backends/mysql/operations.py
  38. +1 −1  django/contrib/gis/db/backends/oracle/operations.py
  39. +11 −30 django/contrib/gis/db/backends/postgis/operations.py
  40. +3 −3 django/contrib/gis/db/backends/spatialite/creation.py
  41. +1 −1  django/contrib/gis/db/backends/spatialite/operations.py
  42. +3 −2 django/contrib/gis/db/models/query.py
  43. +3 −2 django/contrib/gis/db/models/sql/compiler.py
  44. +2 −3 django/contrib/gis/gdal/geometries.py
  45. +2 −1  django/contrib/gis/geometry/test_data.py
  46. +9 −5 django/contrib/gis/measure.py
  47. +4 −3 django/contrib/gis/sitemaps/views.py
  48. +7 −7 django/contrib/gis/tests/geoapp/test_regress.py
  49. +404 −397 django/contrib/gis/tests/geoapp/tests.py
  50. +2 −2 django/contrib/humanize/templatetags/humanize.py
  51. +2 −2 django/contrib/localflavor/au/forms.py
  52. +6 −6 django/contrib/localflavor/br/forms.py
  53. +2 −2 django/contrib/localflavor/ca/forms.py
  54. +2 −2 django/contrib/localflavor/ch/forms.py
  55. +2 −2 django/contrib/localflavor/cl/forms.py
  56. +2 −2 django/contrib/localflavor/fr/forms.py
  57. +2 −2 django/contrib/localflavor/hk/forms.py
  58. +3 −3 django/contrib/localflavor/hr/forms.py
  59. +5 −5 django/contrib/localflavor/id/forms.py
  60. +3 −3 django/contrib/localflavor/in_/forms.py
  61. +2 −2 django/contrib/localflavor/is_/forms.py
  62. +2 −2 django/contrib/localflavor/it/forms.py
  63. +3 −3 django/contrib/localflavor/it/util.py
  64. +2 −2 django/contrib/localflavor/nl/forms.py
  65. +3 −3 django/contrib/localflavor/pt/forms.py
  66. +1 −1  django/contrib/localflavor/si/forms.py
  67. +2 −2 django/contrib/localflavor/tr/forms.py
  68. +2 −2 django/contrib/localflavor/us/forms.py
  69. +10 −10 django/contrib/markup/templatetags/markup.py
  70. +7 −7 django/contrib/messages/storage/base.py
  71. +2 −1  django/contrib/messages/storage/cookie.py
  72. +2 −2 django/contrib/sessions/backends/db.py
  73. +10 −9 django/contrib/sessions/tests.py
  74. +2 −1  django/contrib/sitemaps/views.py
  75. +2 −1  django/contrib/staticfiles/finders.py
  76. +5 −4 django/contrib/staticfiles/management/commands/collectstatic.py
  77. +3 −3 django/contrib/staticfiles/management/commands/findstatic.py
  78. +5 −5 django/contrib/staticfiles/storage.py
  79. +6 −6 django/contrib/syndication/views.py
  80. +3 −3 django/core/cache/backends/base.py
  81. +2 −2 django/core/context_processors.py
  82. +3 −3 django/core/exceptions.py
  83. +7 −5 django/core/files/base.py
  84. +6 −1 django/core/files/images.py
  85. +2 −2 django/core/files/storage.py
  86. +2 −2 django/core/files/uploadedfile.py
  87. +4 −4 django/core/handlers/base.py
  88. +4 −4 django/core/handlers/wsgi.py
  89. +19 −19 django/core/mail/message.py
  90. +3 −2 django/core/management/__init__.py
  91. +2 −2 django/core/management/base.py
  92. +3 −1 django/core/management/commands/compilemessages.py
  93. +2 −2 django/core/management/commands/createcachetable.py
  94. +1 −3 django/core/management/commands/diffsettings.py
  95. +2 −1  django/core/management/commands/flush.py
  96. +2 −2 django/core/management/commands/loaddata.py
  97. +3 −2 django/core/serializers/__init__.py
  98. +4 −2 django/core/serializers/base.py
  99. +1 −1  django/core/serializers/json.py
  100. +11 −10 django/core/serializers/python.py
  101. +1 −1  django/core/serializers/pyyaml.py
  102. +12 −10 django/core/serializers/xml_serializer.py
  103. +6 −6 django/core/signing.py
  104. +7 −7 django/core/urlresolvers.py
  105. +4 −4 django/core/validators.py
  106. +5 −5 django/db/backends/__init__.py
  107. +2 −1  django/db/backends/creation.py
  108. +2 −1  django/db/backends/mysql/introspection.py
  109. +12 −10 django/db/backends/oracle/base.py
  110. +3 −2 django/db/backends/oracle/creation.py
  111. +9 −9 django/db/backends/sqlite3/base.py
  112. +2 −1  django/db/backends/sqlite3/creation.py
  113. +33 −32 django/db/models/base.py
  114. +13 −12 django/db/models/deletion.py
  115. +12 −9 django/db/models/fields/__init__.py
  116. +2 −2 django/db/models/fields/files.py
  117. +7 −7 django/db/models/fields/related.py
  118. +3 −2 django/db/models/loading.py
  119. +11 −12 django/db/models/options.py
  120. +12 −11 django/db/models/query.py
  121. +3 −2 django/db/models/query_utils.py
  122. +3 −3 django/db/models/related.py
  123. +4 −3 django/db/models/sql/compiler.py
  124. +15 −14 django/db/models/sql/query.py
  125. +6 −5 django/db/models/sql/subqueries.py
  126. +2 −1  django/dispatch/saferef.py
  127. +1 −1  django/forms/extras/widgets.py
  128. +14 −24 django/forms/fields.py
  129. +13 −15 django/forms/forms.py
  130. +3 −2 django/forms/formsets.py
  131. +22 −22 django/forms/models.py
  132. +6 −6 django/forms/util.py
  133. +26 −26 django/forms/widgets.py
  134. +35 −26 django/http/__init__.py
  135. +17 −9 django/http/multipartparser.py
  136. +7 −7 django/template/base.py
  137. +2 −2 django/template/debug.py
  138. +9 −9 django/template/defaultfilters.py
  139. +6 −5 django/template/defaulttags.py
  140. +3 −2 django/template/loader_tags.py
  141. +6 −2 django/template/loaders/app_directories.py
  142. +1 −1  django/templatetags/i18n.py
  143. +3 −3 django/templatetags/l10n.py
  144. +103 −16 django/test/_doctest.py
  145. +7 −7 django/test/client.py
  146. +4 −2 django/test/html.py
  147. +7 −6 django/test/testcases.py
  148. +10 −10 django/utils/_os.py
  149. +3 −4 django/utils/archive.py
  150. +2 −2 django/utils/cache.py
  151. +9 −8 django/utils/crypto.py
  152. +1 −1  django/utils/datastructures.py
  153. +3 −3 django/utils/dateformat.py
  154. +4 −3 django/utils/dateparse.py
  155. +1 −1  django/utils/dictconfig.py
  156. +43 −25 django/utils/encoding.py
  157. +21 −16 django/utils/feedgenerator.py
  158. +40 −24 django/utils/functional.py
  159. +13 −13 django/utils/html.py
  160. +15 −9 django/utils/http.py
  161. +6 −5 django/utils/regex_helper.py
  162. +2 −2 django/utils/safestring.py
  163. +1 −0  django/utils/six.py
  164. +3 −1 django/utils/termcolors.py
  165. +12 −12 django/utils/text.py
  166. +2 −2 django/utils/translation/__init__.py
  167. +3 −3 django/utils/translation/trans_null.py
  168. +24 −17 django/utils/translation/trans_real.py
  169. +2 −1  django/utils/tree.py
  170. +2 −2 django/utils/tzinfo.py
  171. +5 −5 django/views/debug.py
  172. +2 −1  django/views/generic/base.py
  173. +3 −3 django/views/generic/dates.py
  174. +3 −3 django/views/i18n.py
  175. +2 −1  docs/faq/index.txt
  176. +16 −0 docs/faq/troubleshooting.txt
  177. +1 −1  docs/howto/custom-model-fields.txt
  178. +105 −36 docs/index.txt
  179. +2 −1  docs/internals/committers.txt
  180. +10 −35 docs/internals/contributing/bugs-and-features.txt
  181. +1 −0  docs/internals/index.txt
  182. +8 −4 docs/internals/release-process.txt
  183. +215 −0 docs/internals/security.txt
  184. BIN  docs/intro/_images/admin15t.png
  185. +2 −1  docs/intro/install.txt
  186. +2 −8 docs/intro/tutorial01.txt
  187. +8 −0 docs/intro/tutorial02.txt
  188. +17 −0 docs/intro/tutorial03.txt
  189. +16 −7 docs/intro/tutorial04.txt
  190. +114 −4 docs/ref/class-based-views/generic-editing.txt
  191. +3 −3 docs/ref/class-based-views/index.txt
  192. +12 −0 docs/ref/class-based-views/mixins-editing.txt
  193. BIN  docs/ref/contrib/admin/_images/article_actions.png
  194. BIN  docs/ref/contrib/admin/_images/article_actions_message.png
  195. BIN  docs/ref/contrib/admin/_images/user_actions.png
  196. +2 −2 docs/ref/contrib/admin/index.txt
  197. +5 −5 docs/ref/contrib/comments/custom.txt
  198. +11 −0 docs/ref/contrib/gis/geos.txt
  199. +2 −0  docs/ref/contrib/gis/install.txt
  200. +5 −4 docs/ref/contrib/humanize.txt
  201. +8 −6 docs/ref/contrib/messages.txt
  202. +1 −1  docs/ref/databases.txt
  203. +1 −1  docs/ref/django-admin.txt
  204. +12 −9 docs/ref/forms/api.txt
  205. +6 −4 docs/ref/forms/validation.txt
  206. +1 −1  docs/ref/middleware.txt
  207. +35 −26 docs/ref/models/fields.txt
  208. +2 −2 docs/ref/models/instances.txt
  209. +1 −1  docs/ref/settings.txt
  210. +1 −1  docs/ref/templates/builtins.txt
  211. +12 −12 docs/ref/unicode.txt
  212. +43 −13 docs/ref/utils.txt
  213. +15 −2 docs/releases/1.5.txt
  214. +50 −34 docs/topics/auth.txt
  215. +3 −2 docs/topics/cache.txt
  216. +1 −1  docs/topics/class-based-views/index.txt
  217. +1 −1  docs/topics/db/optimization.txt
  218. +4 −0 docs/topics/forms/modelforms.txt
  219. +4 −1 docs/topics/i18n/formatting.txt
  220. +7 −1 docs/topics/i18n/translation.txt
  221. +5 −0 docs/topics/python3.txt
  222. +2 −2 docs/topics/serialization.txt
  223. +4 −4 tests/modeltests/field_subclassing/fields.py
  224. +2 −2 tests/modeltests/field_subclassing/models.py
  225. +4 −5 tests/modeltests/fixtures/tests.py
  226. +1 −2  tests/modeltests/model_forms/tests.py
  227. +1 −1  tests/modeltests/serializers/tests.py
  228. +5 −4 tests/modeltests/timezones/tests.py
  229. +1 −1  tests/modeltests/user_commands/tests.py
  230. +2 −2 tests/modeltests/validation/models.py
  231. +30 −30 tests/regressiontests/admin_filters/tests.py
  232. +1 −1  tests/regressiontests/admin_views/admin.py
  233. +2 −1  tests/regressiontests/aggregation_regress/tests.py
  234. +2 −2 tests/regressiontests/bash_completion/tests.py
  235. +1 −2  tests/regressiontests/builtin_server/tests.py
  236. +3 −3 tests/regressiontests/cache/tests.py
  237. +1 −2  tests/regressiontests/createsuperuser/tests.py
  238. +2 −1  tests/regressiontests/db_typecasts/tests.py
  239. +1 −1  tests/regressiontests/file_uploads/tests.py
  240. +7 −7 tests/regressiontests/forms/tests/extra.py
  241. +4 −20 tests/regressiontests/forms/tests/forms.py
  242. +17 −2 tests/regressiontests/httpwrappers/tests.py
  243. +4 −4 tests/regressiontests/i18n/commands/compilation.py
  244. +1 −1  tests/regressiontests/i18n/commands/extraction.py
  245. +1 −2  tests/regressiontests/inspectdb/tests.py
  246. +29 −25 tests/regressiontests/mail/tests.py
  247. +2 −2 tests/regressiontests/middleware/tests.py
  248. +4 −0 tests/regressiontests/model_fields/tests.py
  249. +4 −3 tests/regressiontests/multiple_database/tests.py
  250. +1 −1  tests/regressiontests/requests/tests.py
  251. +2 −2 tests/regressiontests/signing/tests.py
  252. +3 −3 tests/regressiontests/staticfiles_tests/tests.py
  253. +3 −3 tests/regressiontests/templates/loaders.py
  254. +3 −3 tests/regressiontests/templates/templatetags/custom.py
  255. +2 −1  tests/regressiontests/templates/tests.py
  256. +1 −1  tests/regressiontests/test_utils/tests.py
  257. +2 −1  tests/regressiontests/utils/baseconv.py
  258. +16 −12 tests/regressiontests/utils/crypto.py
  259. +1 −1  tests/regressiontests/utils/decorators.py
  260. +14 −12 tests/regressiontests/utils/http.py
  261. +18 −8 tests/regressiontests/utils/simplelazyobject.py
  262. +4 −0 tests/regressiontests/views/tests/i18n.py
View
2  django/conf/__init__.py
@@ -158,7 +158,7 @@ def __getattr__(self, name):
return getattr(self.default_settings, name)
def __dir__(self):
- return self.__dict__.keys() + dir(self.default_settings)
+ return list(self.__dict__) + dir(self.default_settings)
# For Python < 2.6:
__members__ = property(lambda self: self.__dir__())
View
2  django/conf/locale/fi/formats.py
@@ -7,7 +7,7 @@
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j. E Y'
TIME_FORMAT = 'G.i.s'
-# DATETIME_FORMAT =
+DATETIME_FORMAT = r'j. E Y \k\e\l\l\o G.i.s'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT = 'j.n.Y'
View
15 django/conf/locale/gl/formats.py
@@ -1,17 +1,18 @@
# -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
+from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
-DATE_FORMAT = 'd F Y'
+DATE_FORMAT = r'j \d\e F \d\e Y'
TIME_FORMAT = 'H:i:s'
-# DATETIME_FORMAT =
-YEAR_MONTH_FORMAT = 'F Y'
-MONTH_DAY_FORMAT = 'j F'
-SHORT_DATE_FORMAT = 'j M, Y'
-# SHORT_DATETIME_FORMAT =
-# FIRST_DAY_OF_WEEK =
+DATETIME_FORMAT = r'j \d\e F \d\e Y \s H:i'
+YEAR_MONTH_FORMAT = r'F \d\e Y'
+MONTH_DAY_FORMAT = r'j \d\e F'
+SHORT_DATE_FORMAT = 'd-m-Y'
+SHORT_DATETIME_FORMAT = 'd-m-Y, H:i'
+FIRST_DAY_OF_WEEK = 1 # Monday
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
View
4 django/conf/urls/i18n.py
@@ -1,5 +1,5 @@
from django.conf import settings
-from django.conf.urls import patterns
+from django.conf.urls import patterns, url
from django.core.urlresolvers import LocaleRegexURLResolver
def i18n_patterns(prefix, *args):
@@ -16,5 +16,5 @@ def i18n_patterns(prefix, *args):
urlpatterns = patterns('',
- (r'^setlang/$', 'django.views.i18n.set_language'),
+ url(r'^setlang/$', 'django.views.i18n.set_language', name='set_language'),
)
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
14 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
@@ -94,7 +94,7 @@ def __iter__(self):
class Fieldline(object):
def __init__(self, form, field, readonly_fields=None, model_admin=None):
self.form = form # A django.forms.Form instance
- if not hasattr(field, "__iter__"):
+ if not hasattr(field, "__iter__") or isinstance(field, six.text_type):
self.fields = [field]
else:
self.fields = field
@@ -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:
@@ -325,11 +325,11 @@ class AdminErrorList(forms.util.ErrorList):
"""
def __init__(self, form, inline_formsets):
if form.is_bound:
- self.extend(form.errors.values())
+ self.extend(list(six.itervalues(form.errors)))
for inline_formset in inline_formsets:
self.extend(inline_formset.non_form_errors())
for errors_in_inline_form in inline_formset.errors:
- self.extend(errors_in_inline_form.values())
+ self.extend(list(six.itervalues(errors_in_inline_form)))
def normalize_fieldsets(fieldsets):
"""
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
64 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
@@ -425,7 +425,7 @@ def get_fieldsets(self, request, obj=None):
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_form(request, obj)
- fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj))
+ fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
def get_form(self, request, obj=None, **kwargs):
@@ -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
@@ -608,7 +608,7 @@ def get_action_choices(self, request, default_choices=BLANK_CHOICE_DASH):
tuple (name, description).
"""
choices = [] + default_choices
- for func, name, description in self.get_actions(request).itervalues():
+ for func, name, description in six.itervalues(self.get_actions(request)):
choice = (name, description % model_format_dict(self.opts))
choices.append(choice)
return choices
@@ -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,
@@ -1415,7 +1415,7 @@ def get_fieldsets(self, request, obj=None):
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_formset(request, obj).form
- fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj))
+ fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
def queryset(self, request):
View
7 django/contrib/admin/sites.py
@@ -10,6 +10,7 @@
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template.response import TemplateResponse
from django.utils.safestring import mark_safe
+from django.utils import six
from django.utils.text import capfirst
from django.utils.translation import ugettext as _
from django.views.decorators.cache import never_cache
@@ -133,7 +134,7 @@ def actions(self):
"""
Get all the enabled actions as an iterable of (name, func).
"""
- return self._actions.iteritems()
+ return six.iteritems(self._actions)
def has_permission(self, request):
"""
@@ -239,7 +240,7 @@ def wrapper(*args, **kwargs):
)
# Add in each model's views.
- for model, model_admin in self._registry.iteritems():
+ for model, model_admin in six.iteritems(self._registry):
urlpatterns += patterns('',
url(r'^%s/%s/' % (model._meta.app_label, model._meta.module_name),
include(model_admin.urls))
@@ -370,7 +371,7 @@ def index(self, request, extra_context=None):
}
# Sort the apps alphabetically.
- app_list = app_dict.values()
+ app_list = list(six.itervalues(app_dict))
app_list.sort(key=lambda x: x['name'])
# Sort the models alphabetically within each app.
View
15 django/contrib/admin/templatetags/admin_list.py
@@ -12,9 +12,10 @@
from django.utils import formats
from django.utils.html import format_html
from django.utils.safestring import mark_safe
+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
@@ -125,7 +126,7 @@ def result_headers(cl):
if i in ordering_field_columns:
sorted = True
order_type = ordering_field_columns.get(i).lower()
- sort_priority = ordering_field_columns.keys().index(i) + 1
+ sort_priority = list(ordering_field_columns).index(i) + 1
th_classes.append('sorted %sending' % order_type)
new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type]
@@ -209,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:
@@ -223,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,
@@ -240,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
@@ -266,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
5 django/contrib/admindocs/views.py
@@ -14,6 +14,7 @@
from django.contrib.admindocs import utils
from django.contrib.sites.models import Site
from django.utils.importlib import import_module
+from django.utils import six
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
@@ -48,7 +49,7 @@ def template_tag_index(request):
load_all_installed_template_libraries()
tags = []
- app_libs = template.libraries.items()
+ app_libs = list(six.iteritems(template.libraries))
builtin_libs = [(None, lib) for lib in template.builtins]
for module_name, library in builtin_libs + app_libs:
for tag_name, tag_func in library.tags.items():
@@ -83,7 +84,7 @@ def template_filter_index(request):
load_all_installed_template_libraries()
filters = []
- app_libs = template.libraries.items()
+ app_libs = list(six.iteritems(template.libraries))
builtin_libs = [(None, lib) for lib in template.builtins]
for module_name, library in builtin_libs + app_libs:
for filter_name, filter_func in library.filters.items():
View
3  django/contrib/auth/admin.py
@@ -12,6 +12,7 @@
from django.utils.html import escape
from django.utils.decorators import method_decorator
from django.utils.safestring import mark_safe
+from django.utils import six
from django.utils.translation import ugettext, ugettext_lazy as _
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
@@ -128,7 +129,7 @@ def user_change_password(self, request, id, form_url=''):
else:
form = self.change_password_form(user)
- fieldsets = [(None, {'fields': form.base_fields.keys()})]
+ fieldsets = [(None, {'fields': list(form.base_fields)})]
adminForm = admin.helpers.AdminForm(form, fieldsets, {})
context = {
View
3  django/contrib/auth/context_processors.py
@@ -11,8 +11,9 @@ def __repr__(self):
def __getitem__(self, perm_name):
return self.user.has_perm("%s.%s" % (self.module_name, perm_name))
- def __nonzero__(self):
+ def __bool__(self):
return self.user.has_module_perms(self.module_name)
+ __nonzero__ = __bool__ # Python 2
class PermWrapper(object):
View
6 django/contrib/auth/forms.py
@@ -89,9 +89,9 @@ def clean_username(self):
raise forms.ValidationError(self.error_messages['duplicate_username'])
def clean_password2(self):
- password1 = self.cleaned_data.get("password1", "")
- password2 = self.cleaned_data["password2"]
- if password1 != password2:
+ password1 = self.cleaned_data.get("password1")
+ password2 = self.cleaned_data.get("password2")
+ if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'])
return password2
View
11 django/contrib/auth/hashers.py
@@ -1,5 +1,6 @@
from __future__ import unicode_literals
+import base64
import hashlib
from django.dispatch import receiver
@@ -7,7 +8,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)
@@ -218,7 +219,7 @@ def encode(self, password, salt, iterations=None):
if not iterations:
iterations = self.iterations
hash = pbkdf2(password, salt, iterations, digest=self.digest)
- hash = hash.encode('base64').strip()
+ hash = base64.b64encode(hash).strip()
return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash)
def verify(self, password, encoded):
@@ -298,7 +299,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 +327,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 +361,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
5 django/contrib/auth/management/__init__.py
@@ -9,6 +9,7 @@
from django.contrib.auth import models as auth_app
from django.db.models import get_models, signals
from django.contrib.auth.models import User
+from django.utils.six.moves import input
def _get_permission_codename(action, opts):
@@ -66,10 +67,10 @@ def create_superuser(app, created_models, verbosity, db, **kwargs):
msg = ("\nYou just installed Django's auth system, which means you "
"don't have any superusers defined.\nWould you like to create one "
"now? (yes/no): ")
- confirm = raw_input(msg)
+ confirm = input(msg)
while 1:
if confirm not in ('yes', 'no'):
- confirm = raw_input('Please enter either "yes" or "no": ')
+ confirm = input('Please enter either "yes" or "no": ')
continue
if confirm == 'yes':
call_command("createsuperuser", interactive=True, database=db)
View
5 django/contrib/auth/management/commands/createsuperuser.py
@@ -12,6 +12,7 @@
from django.core import exceptions
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS
+from django.utils.six.moves import input
from django.utils.translation import ugettext as _
RE_VALID_USERNAME = re.compile('[\w.@+-]+$')
@@ -76,7 +77,7 @@ def handle(self, *args, **options):
input_msg = 'Username'
if default_username:
input_msg += ' (leave blank to use %r)' % default_username
- username = raw_input(input_msg + ': ')
+ username = input(input_msg + ': ')
if default_username and username == '':
username = default_username
if not RE_VALID_USERNAME.match(username):
@@ -94,7 +95,7 @@ def handle(self, *args, **options):
# Get an email
while 1:
if not email:
- email = raw_input('E-mail address: ')
+ email = input('E-mail address: ')
try:
is_valid_email(email)
except exceptions.ValidationError:
View
32 django/contrib/auth/tests/forms.py
@@ -8,7 +8,8 @@
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 _
@@ -27,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 = {
@@ -38,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.
@@ -50,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)
@@ -65,6 +66,7 @@ def test_both_passwords(self):
form = UserCreationForm(data)
self.assertFalse(form.is_valid())
self.assertEqual(form['password1'].errors, required_error)
+ self.assertEqual(form['password2'].errors, [])
def test_success(self):
# The success case.
@@ -94,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.
@@ -105,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):
@@ -118,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
@@ -146,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')
@@ -173,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.
@@ -186,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.
@@ -202,7 +204,7 @@ def test_success(self):
def test_field_order(self):
# Regression test - check the order of fields:
user = User.objects.get(username='testclient')
- self.assertEqual(PasswordChangeForm(user, {}).fields.keys(),
+ self.assertEqual(list(PasswordChangeForm(user, {}).fields),
['old_password', 'new_password1', 'new_password2'])
@@ -217,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
@@ -272,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
@@ -280,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
12 django/contrib/contenttypes/management.py
@@ -1,6 +1,8 @@
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
+from django.utils.six.moves import input
def update_contenttypes(app, created_models, verbosity=2, **kwargs):
"""
@@ -24,17 +26,17 @@ def update_contenttypes(app, created_models, verbosity=2, **kwargs):
)
to_remove = [
ct
- for (model_name, ct) in content_types.iteritems()
+ for (model_name, ct) in six.iteritems(content_types)
if model_name not in app_models
]
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,
)
- for (model_name, model) in app_models.iteritems()
+ for (model_name, model) in six.iteritems(app_models)
if model_name not in content_types
])
if verbosity >= 2:
@@ -48,7 +50,7 @@ def update_contenttypes(app, created_models, verbosity=2, **kwargs):
' %s | %s' % (ct.app_label, ct.model)
for ct in to_remove
])
- ok_to_delete = raw_input("""The following content types are stale and need to be deleted:
+ ok_to_delete = input("""The following content types are stale and need to be deleted:
%s
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
24 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)'
@@ -17,12 +17,12 @@ class EasyModel(object):
def __init__(self, site, model):
self.site = site
self.model = model
- self.model_list = site.registry.keys()
+ self.model_list = list(site.registry.keys())
self.verbose_name = model._meta.verbose_name
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):
"""
@@ -176,8 +176,6 @@ def urls(self):
for plugin_name, plugin in self.model.model_databrowse().plugins.items():
urls = plugin.urls(plugin_name, self)
if urls is not None:
- #plugin_urls.append(urls)
- values = self.values()
return zip(self.values(), urls)
if self.field.rel:
m = EasyModel(self.model.site, self.field.rel.to)
@@ -187,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:
@@ -196,10 +194,10 @@ def urls(self):
url = '%s%s/%s/fields/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.name, iri_to_uri(self.raw_value))
lst.append((value, url))
elif isinstance(self.field, models.URLField):
- val = self.values()[0]
+ val = list(self.values())[0]
lst = [(val, iri_to_uri(val))]
else:
- lst = [(self.values()[0], None)]
+ lst = [(list(self.values())[0], None)]
return lst
class EasyQuerySet(QuerySet):
View
6 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):
@@ -96,7 +96,7 @@ def model_view(self, request, model_databrowse, url):
def homepage_view(self, request):
easy_model = EasyModel(self.site, self.model)
- field_list = self.fields.values()
+ field_list = list(self.fields.values())
field_list.sort(key=lambda k:k.verbose_name)
return render_to_response('databrowse/calendar_homepage.html', {
'root_url': self.site.root_url,
View
6 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():
@@ -63,7 +63,7 @@ def model_view(self, request, model_databrowse, url):
def homepage_view(self, request):
easy_model = EasyModel(self.site, self.model)
- field_list = self.fields.values()
+ field_list = list(self.fields.values())
field_list.sort(key=lambda k: k.verbose_name)
return render_to_response('databrowse/fieldchoice_homepage.html', {'root_url': self.site.root_url, 'model': easy_model, 'field_list': field_list})
View
2  django/contrib/formtools/tests/__init__.py
@@ -317,7 +317,7 @@ def test_14498(self):
class WizardWithProcessStep(TestWizardClass):
def process_step(self, request, form, step):
- that.assertTrue(hasattr(form, 'cleaned_data'))
+ that.assertTrue(form.is_valid())
reached[0] = True
wizard = WizardWithProcessStep([WizardPageOneForm,
View
11 django/contrib/formtools/wizard/storage/base.py
@@ -1,7 +1,8 @@
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
from django.contrib.formtools.wizard.storage.exceptions import NoFileStorageConfigured
@@ -72,9 +73,9 @@ def get_step_files(self, step):
raise NoFileStorageConfigured
files = {}
- for field, field_dict in wizard_files.iteritems():
- field_dict = dict((smart_str(k), v)
- for k, v in field_dict.iteritems())
+ for field, field_dict in six.iteritems(wizard_files):
+ 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(
file=self.file_storage.open(tmp_name), **field_dict)
@@ -87,7 +88,7 @@ def set_step_files(self, step, files):
if step not in self.data[self.step_files_key]:
self.data[self.step_files_key][step] = {}
- for field, field_file in (files or {}).iteritems():
+ for field, field_file in six.iteritems(files or {}):
tmp_filename = self.file_storage.save(field_file.name, field_file)
file_dict = {
'tmp_name': tmp_filename,
View
8 django/contrib/formtools/wizard/views.py
<
@@ -44,7 +44,7 @@ def __repr__(self):
@property
def all(self):
"Returns the names of all steps/forms."
- return self._wizard.get_form_list().keys()