Changeset 5609
- Timestamp:
- 07/04/07 07:11:04 (2 years ago)
- Files:
-
- django/trunk (modified) (1 prop)
- django/trunk/AUTHORS (modified) (2 diffs)
- django/trunk/django/bin/make-messages.py (modified) (1 diff)
- django/trunk/django/conf/global_settings.py (modified) (1 diff)
- django/trunk/django/contrib/admin/filterspecs.py (modified) (5 diffs)
- django/trunk/django/contrib/admin/media/js/urlify.js (modified) (3 diffs)
- django/trunk/django/contrib/admin/models.py (modified) (4 diffs)
- django/trunk/django/contrib/admin/templates/admin/filter.html (modified) (1 diff)
- django/trunk/django/contrib/admin/templatetags/adminapplist.py (modified) (2 diffs)
- django/trunk/django/contrib/admin/templatetags/admin_list.py (modified) (6 diffs)
- django/trunk/django/contrib/admin/templatetags/admin_modify.py (modified) (8 diffs)
- django/trunk/django/contrib/admin/views/auth.py (modified) (1 diff)
- django/trunk/django/contrib/admin/views/decorators.py (modified) (1 diff)
- django/trunk/django/contrib/admin/views/doc.py (modified) (1 diff)
- django/trunk/django/contrib/admin/views/main.py (modified) (19 diffs)
- django/trunk/django/contrib/auth/forms.py (modified) (1 diff)
- django/trunk/django/contrib/auth/management.py (modified) (2 diffs)
- django/trunk/django/contrib/auth/models.py (modified) (12 diffs)
- django/trunk/django/contrib/auth/views.py (modified) (1 diff)
- django/trunk/django/contrib/comments/feeds.py (modified) (2 diffs)
- django/trunk/django/contrib/comments/models.py (modified) (1 diff)
- django/trunk/django/contrib/comments/views/comments.py (modified) (4 diffs)
- django/trunk/django/contrib/comments/views/karma.py (modified) (1 diff)
- django/trunk/django/contrib/contenttypes/generic.py (modified) (2 diffs)
- django/trunk/django/contrib/contenttypes/management.py (modified) (2 diffs)
- django/trunk/django/contrib/contenttypes/models.py (modified) (3 diffs)
- django/trunk/django/contrib/databrowse/datastructures.py (modified) (9 diffs)
- django/trunk/django/contrib/databrowse/plugins/calendars.py (modified) (2 diffs)
- django/trunk/django/contrib/databrowse/plugins/fieldchoices.py (modified) (2 diffs)
- django/trunk/django/contrib/databrowse/sites.py (modified) (1 diff)
- django/trunk/django/contrib/databrowse/templates/databrowse/fieldchoice_list.html (modified) (1 diff)
- django/trunk/django/contrib/flatpages/models.py (modified) (2 diffs)
- django/trunk/django/contrib/humanize/templatetags/humanize.py (modified) (4 diffs)
- django/trunk/django/contrib/localflavor/au/forms.py (modified) (3 diffs)
- django/trunk/django/contrib/localflavor/br/forms.py (modified) (8 diffs)
- django/trunk/django/contrib/localflavor/ch/ch_states.py (modified) (1 diff)
- django/trunk/django/contrib/localflavor/ch/forms.py (modified) (3 diffs)
- django/trunk/django/contrib/localflavor/cl/forms.py (modified) (5 diffs)
- django/trunk/django/contrib/localflavor/de/de_states.py (modified) (1 diff)
- django/trunk/django/contrib/localflavor/de/forms.py (modified) (5 diffs)
- django/trunk/django/contrib/localflavor/fi/forms.py (modified) (4 diffs)
- django/trunk/django/contrib/localflavor/fr/forms.py (modified) (3 diffs)
- django/trunk/django/contrib/localflavor/is_/forms.py (modified) (4 diffs)
- django/trunk/django/contrib/localflavor/it/forms.py (modified) (6 diffs)
- django/trunk/django/contrib/localflavor/it/it_province.py (modified) (1 diff)
- django/trunk/django/contrib/localflavor/it/util.py (modified) (4 diffs)
- django/trunk/django/contrib/localflavor/jp/forms.py (modified) (2 diffs)
- django/trunk/django/contrib/localflavor/jp/jp_prefectures.py (modified) (1 diff)
- django/trunk/django/contrib/localflavor/no/forms.py (modified) (5 diffs)
- django/trunk/django/contrib/localflavor/no/no_municipalities.py (modified) (3 diffs)
- django/trunk/django/contrib/localflavor/uk/forms.py (modified) (2 diffs)
- django/trunk/django/contrib/localflavor/us/forms.py (modified) (6 diffs)
- django/trunk/django/contrib/markup/templatetags/markup.py (modified) (4 diffs)
- django/trunk/django/contrib/redirects/models.py (modified) (2 diffs)
- django/trunk/django/contrib/sessions/models.py (modified) (1 diff)
- django/trunk/django/contrib/sitemaps/views.py (modified) (2 diffs)
- django/trunk/django/contrib/sites/models.py (modified) (2 diffs)
- django/trunk/django/contrib/syndication/feeds.py (modified) (3 diffs)
- django/trunk/django/contrib/webdesign/lorem_ipsum.py (modified) (4 diffs)
- django/trunk/django/contrib/webdesign/templatetags/webdesign.py (modified) (1 diff)
- django/trunk/django/contrib/webdesign/tests.py (modified) (1 diff)
- django/trunk/django/core/handlers/modpython.py (modified) (3 diffs)
- django/trunk/django/core/handlers/wsgi.py (modified) (3 diffs)
- django/trunk/django/core/mail.py (modified) (6 diffs)
- django/trunk/django/core/management.py (modified) (1 diff)
- django/trunk/django/core/serializers/base.py (modified) (3 diffs)
- django/trunk/django/core/serializers/__init__.py (modified) (3 diffs)
- django/trunk/django/core/serializers/python.py (modified) (7 diffs)
- django/trunk/django/core/serializers/pyyaml.py (modified) (2 diffs)
- django/trunk/django/core/serializers/xml_serializer.py (modified) (17 diffs)
- django/trunk/django/core/urlresolvers.py (modified) (4 diffs)
- django/trunk/django/core/validators.py (modified) (32 diffs)
- django/trunk/django/db/backends/mysql/base.py (modified) (1 diff)
- django/trunk/django/db/backends/mysql_old/base.py (modified) (2 diffs)
- django/trunk/django/db/backends/oracle/base.py (modified) (6 diffs)
- django/trunk/django/db/backends/oracle/creation.py (modified) (2 diffs)
- django/trunk/django/db/backends/postgresql/base.py (modified) (9 diffs)
- django/trunk/django/db/backends/postgresql_psycopg2/base.py (modified) (3 diffs)
- django/trunk/django/db/backends/sqlite3/base.py (modified) (5 diffs)
- django/trunk/django/db/backends/util.py (modified) (4 diffs)
- django/trunk/django/db/models/base.py (modified) (4 diffs)
- django/trunk/django/db/models/fields/__init__.py (modified) (19 diffs)
- django/trunk/django/db/models/fields/related.py (modified) (4 diffs)
- django/trunk/django/db/models/manipulators.py (modified) (3 diffs)
- django/trunk/django/db/models/options.py (modified) (4 diffs)
- django/trunk/django/db/models/query.py (modified) (2 diffs)
- django/trunk/django/http/__init__.py (modified) (13 diffs)
- django/trunk/django/newforms/fields.py (modified) (21 diffs)
- django/trunk/django/newforms/forms.py (modified) (4 diffs)
- django/trunk/django/newforms/models.py (modified) (5 diffs)
- django/trunk/django/newforms/util.py (modified) (3 diffs)
- django/trunk/django/newforms/widgets.py (modified) (13 diffs)
- django/trunk/django/oldforms/__init__.py (modified) (24 diffs)
- django/trunk/django/template/defaultfilters.py (modified) (25 diffs)
- django/trunk/django/template/defaulttags.py (modified) (3 diffs)
- django/trunk/django/template/__init__.py (modified) (7 diffs)
- django/trunk/django/template/loaders/app_directories.py (modified) (1 diff)
- django/trunk/django/template/loaders/eggs.py (modified) (1 diff)
- django/trunk/django/template/loaders/filesystem.py (modified) (1 diff)
- django/trunk/django/templatetags/i18n.py (modified) (3 diffs)
- django/trunk/django/test/client.py (modified) (6 diffs)
- django/trunk/django/test/testcases.py (modified) (2 diffs)
- django/trunk/django/test/utils.py (modified) (1 diff)
- django/trunk/django/utils/cache.py (modified) (2 diffs)
- django/trunk/django/utils/dateformat.py (modified) (13 diffs)
- django/trunk/django/utils/dates.py (modified) (1 diff)
- django/trunk/django/utils/encoding.py (modified) (2 diffs)
- django/trunk/django/utils/feedgenerator.py (modified) (5 diffs)
- django/trunk/django/utils/functional.py (modified) (4 diffs)
- django/trunk/django/utils/html.py (modified) (6 diffs)
- django/trunk/django/utils/http.py (copied) (copied from django/branches/unicode/django/utils/http.py)
- django/trunk/django/utils/stopwords.py (modified) (1 diff)
- django/trunk/django/utils/text.py (modified) (12 diffs)
- django/trunk/django/utils/timesince.py (modified) (4 diffs)
- django/trunk/django/utils/translation/__init__.py (modified) (3 diffs)
- django/trunk/django/utils/translation/trans_null.py (modified) (3 diffs)
- django/trunk/django/utils/translation/trans_real.py (modified) (9 diffs)
- django/trunk/django/utils/tzinfo.py (modified) (4 diffs)
- django/trunk/django/views/debug.py (modified) (3 diffs)
- django/trunk/django/views/generic/create_update.py (modified) (4 diffs)
- django/trunk/docs/contributing.txt (modified) (1 diff)
- django/trunk/docs/db-api.txt (modified) (3 diffs)
- django/trunk/docs/forms.txt (modified) (1 diff)
- django/trunk/docs/i18n.txt (modified) (15 diffs)
- django/trunk/docs/model-api.txt (modified) (4 diffs)
- django/trunk/docs/newforms.txt (modified) (1 diff)
- django/trunk/docs/overview.txt (modified) (2 diffs)
- django/trunk/docs/settings.txt (modified) (1 diff)
- django/trunk/docs/templates.txt (modified) (1 diff)
- django/trunk/docs/tutorial01.txt (modified) (2 diffs)
- django/trunk/docs/unicode.txt (copied) (copied from django/branches/unicode/docs/unicode.txt)
- django/trunk/tests/modeltests/basic/models.py (modified) (3 diffs)
- django/trunk/tests/modeltests/choices/models.py (modified) (2 diffs)
- django/trunk/tests/modeltests/custom_columns/models.py (modified) (4 diffs)
- django/trunk/tests/modeltests/custom_managers/models.py (modified) (3 diffs)
- django/trunk/tests/modeltests/custom_methods/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/custom_pk/models.py (modified) (4 diffs)
- django/trunk/tests/modeltests/field_defaults/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/fixtures/models.py (modified) (5 diffs)
- django/trunk/tests/modeltests/generic_relations/models.py (modified) (7 diffs)
- django/trunk/tests/modeltests/get_latest/models.py (modified) (2 diffs)
- django/trunk/tests/modeltests/get_object_or_404/models.py (modified) (2 diffs)
- django/trunk/tests/modeltests/get_or_create/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/lookup/models.py (modified) (4 diffs)
- django/trunk/tests/modeltests/m2m_and_m2o/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/m2m_intermediary/models.py (modified) (3 diffs)
- django/trunk/tests/modeltests/m2m_multiple/models.py (modified) (2 diffs)
- django/trunk/tests/modeltests/m2m_recursive/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/m2o_recursive2/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/m2o_recursive/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/manipulators/models.py (modified) (3 diffs)
- django/trunk/tests/modeltests/many_to_many/models.py (modified) (2 diffs)
- django/trunk/tests/modeltests/many_to_one/models.py (modified) (4 diffs)
- django/trunk/tests/modeltests/many_to_one_null/models.py (modified) (2 diffs)
- django/trunk/tests/modeltests/model_forms/models.py (modified) (6 diffs)
- django/trunk/tests/modeltests/model_inheritance/models.py (modified) (2 diffs)
- django/trunk/tests/modeltests/one_to_one/models.py (modified) (3 diffs)
- django/trunk/tests/modeltests/ordering/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/or_lookups/models.py (modified) (2 diffs)
- django/trunk/tests/modeltests/pagination/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/reserved_names/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/reverse_lookup/models.py (modified) (3 diffs)
- django/trunk/tests/modeltests/save_delete_hooks/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/select_related/models.py (modified) (8 diffs)
- django/trunk/tests/modeltests/serializers/models.py (modified) (4 diffs)
- django/trunk/tests/modeltests/str/models.py (modified) (3 diffs)
- django/trunk/tests/modeltests/test_client/models.py (modified) (2 diffs)
- django/trunk/tests/modeltests/test_client/views.py (modified) (1 diff)
- django/trunk/tests/modeltests/transactions/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/validation/models.py (modified) (6 diffs)
- django/trunk/tests/regressiontests/dateformat/tests.py (modified) (3 diffs)
- django/trunk/tests/regressiontests/defaultfilters/tests.py (modified) (8 diffs)
- django/trunk/tests/regressiontests/fixtures_regress/models.py (modified) (1 diff)
- django/trunk/tests/regressiontests/forms/localflavor.py (modified) (3 diffs)
- django/trunk/tests/regressiontests/forms/regressions.py (modified) (1 diff)
- django/trunk/tests/regressiontests/forms/tests.py (modified) (1 diff)
- django/trunk/tests/regressiontests/httpwrappers/tests.py (modified) (15 diffs)
- django/trunk/tests/regressiontests/humanize/tests.py (modified) (3 diffs)
- django/trunk/tests/regressiontests/i18n (copied) (copied from django/branches/unicode/tests/regressiontests/i18n)
- django/trunk/tests/regressiontests/i18n/__init__.py (copied) (copied from django/branches/unicode/tests/regressiontests/i18n/__init__.py)
- django/trunk/tests/regressiontests/i18n/models.py (copied) (copied from django/branches/unicode/tests/regressiontests/i18n/models.py)
- django/trunk/tests/regressiontests/i18n/tests.py (copied) (copied from django/branches/unicode/tests/regressiontests/i18n/tests.py)
- django/trunk/tests/regressiontests/model_regress (copied) (copied from django/branches/unicode/tests/regressiontests/model_regress)
- django/trunk/tests/regressiontests/model_regress/__init__.py (copied) (copied from django/branches/unicode/tests/regressiontests/model_regress/__init__.py)
- django/trunk/tests/regressiontests/model_regress/models.py (copied) (copied from django/branches/unicode/tests/regressiontests/model_regress/models.py)
- django/trunk/tests/regressiontests/null_queries/models.py (modified) (2 diffs)
- django/trunk/tests/regressiontests/one_to_one_regress/models.py (modified) (3 diffs)
- django/trunk/tests/regressiontests/serializers_regress/tests.py (modified) (1 diff)
- django/trunk/tests/regressiontests/string_lookup/models.py (modified) (6 diffs)
- django/trunk/tests/regressiontests/templates/tests.py (modified) (4 diffs)
- django/trunk/tests/regressiontests/templates/unicode.py (copied) (copied from django/branches/unicode/tests/regressiontests/templates/unicode.py)
- django/trunk/tests/regressiontests/templates/urls.py (modified) (2 diffs)
- django/trunk/tests/regressiontests/test_client_regress/models.py (modified) (3 diffs)
- django/trunk/tests/regressiontests/test_client_regress/urls.py (modified) (1 diff)
- django/trunk/tests/regressiontests/test_client_regress/views.py (modified) (2 diffs)
- django/trunk/tests/regressiontests/text/tests.py (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/trunk
- Property svnmerge-integrated set to /django/trunk:1-5600
django/trunk/AUTHORS
r5593 r5609 114 114 Owen Griffiths 115 115 Espen Grindhaug <http://grindhaug.org/> 116 Thomas Güttler <hv@tbz-pariv.de> 116 117 Brian Harring <ferringb@gmail.com> 117 118 Brant Harris … … 148 149 Joseph Kocherhans 149 150 konrad@gwu.edu 151 kurtiss@meetro.com 150 152 lakin.wecker@gmail.com 151 153 Nick Lane <nick.lane.au@gmail.com> django/trunk/django/bin/make-messages.py
r5084 r5609 104 104 thefile = '%s.py' % file 105 105 if verbose: sys.stdout.write('processing file %s in %s\n' % (file, dirpath)) 106 cmd = 'xgettext %s -d %s -L Python --keyword=gettext_noop --keyword=gettext_lazy --keyword=ngettext_lazy:1,2 -- from-code UTF-8 -o - "%s"' % (106 cmd = 'xgettext %s -d %s -L Python --keyword=gettext_noop --keyword=gettext_lazy --keyword=ngettext_lazy:1,2 --keyword=ugettext_noop --keyword=ugettext_lazy --keyword=ungettext_lazy:1,2 --from-code UTF-8 -o - "%s"' % ( 107 107 os.path.exists(potfile) and '--omit-header' or '', domain, os.path.join(dirpath, thefile)) 108 108 (stdin, stdout, stderr) = os.popen3(cmd, 'b') django/trunk/django/conf/global_settings.py
r5523 r5609 98 98 DEFAULT_CHARSET = 'utf-8' 99 99 100 # Encoding of files read from disk (template and initial SQL files). 101 FILE_CHARSET = 'utf-8' 102 100 103 # E-mail address that error messages come from. 101 104 SERVER_EMAIL = 'root@localhost' django/trunk/django/contrib/admin/filterspecs.py
r4486 r5609 8 8 9 9 from django.db import models 10 from django.utils.encoding import smart_unicode, iri_to_uri 11 from django.utils.translation import ugettext as _ 10 12 import datetime 11 13 … … 38 40 t = [] 39 41 if self.has_output(): 40 t.append(_( '<h3>By %s:</h3>\n<ul>\n') % self.title())42 t.append(_(u'<h3>By %s:</h3>\n<ul>\n') % self.title()) 41 43 42 44 for choice in self.choices(cl): 43 t.append( '<li%s><a href="%s">%s</a></li>\n' % \45 t.append(u'<li%s><a href="%s">%s</a></li>\n' % \ 44 46 ((choice['selected'] and ' class="selected"' or ''), 45 choice['query_string'],47 iri_to_uri(choice['query_string']), 46 48 choice['display'])) 47 49 t.append('</ul>\n\n') … … 71 73 for val in self.lookup_choices: 72 74 pk_val = getattr(val, self.field.rel.to._meta.pk.attname) 73 yield {'selected': self.lookup_val == s tr(pk_val),75 yield {'selected': self.lookup_val == smart_unicode(pk_val), 74 76 'query_string': cl.get_query_string({self.lookup_kwarg: pk_val}), 75 77 'display': val} … … 88 90 'display': _('All')} 89 91 for k, v in self.field.choices: 90 yield {'selected': s tr(k) == self.lookup_val,92 yield {'selected': smart_unicode(k) == self.lookup_val, 91 93 'query_string': cl.get_query_string({self.lookup_kwarg: k}), 92 94 'display': v} … … 169 171 'display': _('All')} 170 172 for val in self.lookup_choices: 171 val = s tr(val[self.field.name])173 val = smart_unicode(val[self.field.name]) 172 174 yield {'selected': self.lookup_val == val, 173 175 'query_string': cl.get_query_string({self.field.name: val}), django/trunk/django/contrib/admin/media/js/urlify.js
r4537 r5609 1 var LATIN_MAP = 2 { 3 'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', 'Æ': 'AE', 'Ç': 4 'C', 'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I', 'Î': 'I', 5 'Ï': 'I', 'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O', 'Õ': 'O', 'Ö': 6 'O', 'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U', 'Ý': 'Y', 'Þ': 'TH', 7 'ß': 'ss', 'à':'a', 'á':'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'å': 'a', 'æ': 8 'ae', 'ç': 'c', 'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e', 'ì': 'i', 'í': 'i', 9 'î': 'i', 'ï': 'i', 'ð': 'o', 'ñ': 'n', 'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 10 'o', 'ö': 'o', 'ø': 'o', 'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u', 'ý': 'y', 11 'þ': 'th', 'ÿ': 'y', 12 } 13 var LATIN_SYMBOLS_MAP = 14 { 15 '©':'(c)', 16 } 17 var GREEK_MAP = 18 { 19 'α':'a', 'β':'b', 'γ':'g', 'δ':'d', 'ε':'e', 'ζ':'z', 'η':'h', 'θ':'8', 20 'ι':'i', 'κ':'k', 'λ':'l', 'μ':'m', 'ν':'n', 'ξ':'3', 'ο':'o', 'π':'p', 21 'ρ':'r', 'σ':'s', 'τ':'t', 'υ':'y', 'φ':'f', 'χ':'x', 'ψ':'ps', 'ω':'w', 22 'ά':'a', 'έ':'e', 'ί':'i', 'ό':'o', 'ύ':'y', 'ή':'h', 'ώ':'w', 'ς':'s', 23 'ϊ':'i', 'ΰ':'y', 'ϋ':'y', 'ΐ':'i', 24 'Α':'A', 'Β':'B', 'Γ':'G', 'Δ':'D', 'Ε':'E', 'Ζ':'Z', 'Η':'H', 'Θ':'8', 25 'Ι':'I', 'Κ':'K', 'Λ':'L', 'Μ':'M', 'Ν':'N', 'Ξ':'3', 'Ο':'O', 'Π':'P', 26 'Ρ':'R', 'Σ':'S', 'Τ':'T', 'Υ':'Y', 'Φ':'F', 'Χ':'X', 'Ψ':'PS', 'Ω':'W', 27 'Ά':'A', 'Έ':'E', 'Ί':'I', 'Ό':'O', 'Ύ':'Y', 'Ή':'H', 'Ώ':'W', 'Ϊ':'I', 28 'Ϋ':'Y' 29 } 30 var TURKISH_MAP = { 31 'ş':'s', 'Ş':'S', 'ı':'i', 'İ':'I', 'ç':'c', 'Ç':'C', 'ü':'u', 'Ü':'U', 32 'ö':'o', 'Ö':'O', 'ğ':'g', 'Ğ':'G', 33 } 34 // var RUSSIAN_MAP = 35 // { 36 // } 37 38 var ALL_DOWNCODE_MAPS=new Array() 39 ALL_DOWNCODE_MAPS[0]=LATIN_MAP 40 ALL_DOWNCODE_MAPS[1]=LATIN_SYMBOLS_MAP 41 ALL_DOWNCODE_MAPS[2]=GREEK_MAP 42 ALL_DOWNCODE_MAPS[3]=TURKISH_MAP 43 //ALL_DOWNCODE_MAPS[4]=RUSSIAN_MAP 44 45 var Downcoder = new Object(); 46 Downcoder.Initialize = function() 47 { 48 if (Downcoder.map) // already made 49 return ; 50 Downcoder.map ={} 51 Downcoder.chars = '' ; 52 for(var i in ALL_DOWNCODE_MAPS) 53 { 54 var lookup = ALL_DOWNCODE_MAPS[i] 55 for (var c in lookup) 56 { 57 Downcoder.map[c] = lookup[c] ; 58 Downcoder.chars += c ; 59 } 60 } 61 Downcoder.regex = new RegExp('[' + Downcoder.chars + ']|[^' + Downcoder.chars + ']+','g') ; 62 } 63 64 downcode= function( slug ) 65 { 66 Downcoder.Initialize() ; 67 var downcoded ="" 68 var pieces = slug.match(Downcoder.regex); 69 if(pieces) 70 { 71 for (var i = 0 ; i < pieces.length ; i++) 72 { 73 if (pieces[i].length == 1) 74 { 75 var mapped = Downcoder.map[pieces[i]] ; 76 if (mapped != null) 77 { 78 downcoded+=mapped; 79 continue ; 80 } 81 } 82 downcoded+=pieces[i]; 83 } 84 } 85 else 86 { 87 downcoded = slug; 88 } 89 return downcoded; 90 } 91 92 1 93 function URLify(s, num_chars) { 2 94 // changes, e.g., "Petty theft" to "petty_theft" 3 95 // remove all these words from the string before urlifying 96 s = downcode(s); 4 97 removelist = ["a", "an", "as", "at", "before", "but", "by", "for", "from", 5 98 "is", "in", "into", "like", "of", "off", "on", "onto", "per", … … 8 101 r = new RegExp('\\b(' + removelist.join('|') + ')\\b', 'gi'); 9 102 s = s.replace(r, ''); 103 // if downcode doesn't hit, the char will be stripped here 10 104 s = s.replace(/[^-\w\s]/g, ''); // remove unneeded chars 11 105 s = s.replace(/^\s+|\s+$/g, ''); // trim leading/trailing spaces … … 14 108 return s.substring(0, num_chars);// trim to first num_chars chars 15 109 } 110 django/trunk/django/contrib/admin/models.py
r5519 r5609 2 2 from django.contrib.contenttypes.models import ContentType 3 3 from django.contrib.auth.models import User 4 from django.utils.translation import gettext_lazy as _ 4 from django.utils.translation import ugettext_lazy as _ 5 from django.utils.encoding import smart_unicode 5 6 6 7 ADDITION = 1 … … 10 11 class LogEntryManager(models.Manager): 11 12 def log_action(self, user_id, content_type_id, object_id, object_repr, action_flag, change_message=''): 12 e = self.model(None, None, user_id, content_type_id, s tr(object_id), object_repr[:200], action_flag, change_message)13 e = self.model(None, None, user_id, content_type_id, smart_unicode(object_id), object_repr[:200], action_flag, change_message) 13 14 e.save() 14 15 … … 29 30 30 31 def __repr__(self): 31 return s tr(self.action_time)32 return smart_unicode(self.action_time) 32 33 33 34 def is_addition(self): … … 49 50 This is relative to the Django admin index page. 50 51 """ 51 return "%s/%s/%s/" % (self.content_type.app_label, self.content_type.model, self.object_id)52 return u"%s/%s/%s/" % (self.content_type.app_label, self.content_type.model, self.object_id) django/trunk/django/contrib/admin/templates/admin/filter.html
r3349 r5609 4 4 {% for choice in choices %} 5 5 <li{% if choice.selected %} class="selected"{% endif %}> 6 <a href="{{ choice.query_string }}">{{ choice.display|escape }}</a></li>6 <a href="{{ choice.query_string|iriencode }}">{{ choice.display|escape }}</a></li> 7 7 {% endfor %} 8 8 </ul> django/trunk/django/contrib/admin/templatetags/adminapplist.py
r5511 r5609 1 1 from django import template 2 2 from django.db.models import get_models 3 from django.utils.encoding import force_unicode 3 4 4 5 register = template.Library() … … 37 38 if True in perms.values(): 38 39 model_list.append({ 39 'name': capfirst(m._meta.verbose_name_plural),40 'admin_url': '%s/%s/' % (app_label, m.__name__.lower()),40 'name': force_unicode(capfirst(m._meta.verbose_name_plural)), 41 'admin_url': u'%s/%s/' % (force_unicode(app_label), m.__name__.lower()), 41 42 'perms': perms, 42 43 }) django/trunk/django/contrib/admin/templatetags/admin_list.py
r5318 r5609 7 7 from django.utils.html import escape 8 8 from django.utils.text import capfirst 9 from django.utils.translation import get_date_formats, get_partial_date_formats 9 from django.utils.translation import get_date_formats, get_partial_date_formats, ugettext as _ 10 from django.utils.encoding import smart_unicode, smart_str, force_unicode 10 11 from django.template import Library 11 12 import datetime … … 17 18 def paginator_number(cl,i): 18 19 if i == DOT: 19 return '... '20 return u'... ' 20 21 elif i == cl.page_num: 21 return '<span class="this-page">%d</span> ' % (i+1)22 return u'<span class="this-page">%d</span> ' % (i+1) 22 23 else: 23 return '<a href="%s"%s>%d</a> ' % (cl.get_query_string({PAGE_VAR: i}), (i == cl.paginator.pages-1 and ' class="end"' or ''), i+1)24 return u'<a href="%s"%s>%d</a> ' % (cl.get_query_string({PAGE_VAR: i}), (i == cl.paginator.pages-1 and ' class="end"' or ''), i+1) 24 25 paginator_number = register.simple_tag(paginator_number) 25 26 … … 76 77 except models.FieldDoesNotExist: 77 78 # For non-field list_display values, check for the function 78 # attribute "short_description". If that doesn't exist, fall 79 # back to the method name. And __str__ is a special-case. 80 if field_name == '__str__': 81 header = lookup_opts.verbose_name 79 # attribute "short_description". If that doesn't exist, fall back 80 # to the method name. And __str__ and __unicode__ are special-cases. 81 if field_name == '__unicode__': 82 header = force_unicode(lookup_opts.verbose_name) 83 elif field_name == '__str__': 84 header = smart_str(lookup_opts.verbose_name) 82 85 else: 83 86 attr = getattr(cl.model, field_name) # Let AttributeErrors propagate. … … 115 118 def _boolean_icon(field_val): 116 119 BOOLEAN_MAPPING = {True: 'yes', False: 'no', None: 'unknown'} 117 return '<img src="%simg/admin/icon-%s.gif" alt="%s" />' % (settings.ADMIN_MEDIA_PREFIX, BOOLEAN_MAPPING[field_val], field_val)120 return u'<img src="%simg/admin/icon-%s.gif" alt="%s" />' % (settings.ADMIN_MEDIA_PREFIX, BOOLEAN_MAPPING[field_val], field_val) 118 121 119 122 def items_for_result(cl, result): … … 137 140 result_repr = _boolean_icon(attr) 138 141 else: 139 result_repr = s tr(attr)142 result_repr = smart_unicode(attr) 140 143 except (AttributeError, ObjectDoesNotExist): 141 144 result_repr = EMPTY_CHANGELIST_VALUE … … 180 183 result_repr = dict(f.choices).get(field_val, EMPTY_CHANGELIST_VALUE) 181 184 else: 182 result_repr = escape( str(field_val))183 if result_repr== '':185 result_repr = escape(field_val) 186 if force_unicode(result_repr) == '': 184 187 result_repr = ' ' 185 188 # If list_display_links not defined, add the link tag to the first field 186 if (first and not cl.lookup_opts.admin.list_display_links) or field_name in cl.lookup_opts.admin.list_display_links: 189 if (first and not cl.lookup_opts.admin.list_display_links) or field_name in cl.lookup_opts.admin.list_display_links: 187 190 table_tag = {True:'th', False:'td'}[first] 188 191 first = False 189 192 url = cl.url_for_result(result) 190 result_id = s tr(getattr(result, pk)) # str()is needed in case of 23L (long ints)191 yield ( '<%s%s><a href="%s"%s>%s</a></%s>' % \193 result_id = smart_unicode(getattr(result, pk)) # conversion to string is needed in case of 23L (long ints) 194 yield (u'<%s%s><a href="%s"%s>%s</a></%s>' % \ 192 195 (table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %r); return false;"' % result_id or ''), result_repr, table_tag)) 193 196 else: 194 yield ( '<td%s>%s</td>' % (row_class, result_repr))197 yield (u'<td%s>%s</td>' % (row_class, result_repr)) 195 198 196 199 def results(cl): django/trunk/django/contrib/admin/templatetags/admin_modify.py
r5511 r5609 3 3 from django.template import loader 4 4 from django.utils.text import capfirst 5 from django.utils.encoding import force_unicode 5 6 from django.db import models 6 7 from django.db.models.fields import Field … … 15 16 16 17 def class_name_to_underscored(name): 17 return '_'.join([s.lower() for s in word_re.findall(name)[:-1]])18 return u'_'.join([s.lower() for s in word_re.findall(name)[:-1]]) 18 19 19 20 def include_admin_script(script_path): … … 32 33 if not absolute_url_re.match(script_path): 33 34 script_path = '%s%s' % (settings.ADMIN_MEDIA_PREFIX, script_path) 34 return '<script type="text/javascript" src="%s"></script>' % script_path35 return u'<script type="text/javascript" src="%s"></script>' % script_path 35 36 include_admin_script = register.simple_tag(include_admin_script) 36 37 … … 62 63 class_names.append('inline') 63 64 colon = ":" 64 class_str = class_names and ' class="%s"' % ' '.join(class_names) or''65 return '<label for="%s"%s>%s%s</label> ' % (bound_field.element_id, class_str, \66 capfirst(bound_field.field.verbose_name), colon)65 class_str = class_names and u' class="%s"' % u' '.join(class_names) or u'' 66 return u'<label for="%s"%s>%s%s</label> ' % (bound_field.element_id, class_str, \ 67 force_unicode(capfirst(bound_field.field.verbose_name)), colon) 67 68 field_label = register.simple_tag(field_label) 68 69 … … 78 79 try: 79 80 field_class_name = klass.__name__ 80 template_name = "widget/%s.html" % class_name_to_underscored(field_class_name)81 template_name = u"widget/%s.html" % class_name_to_underscored(field_class_name) 81 82 nodelist = loader.get_template(template_name).nodelist 82 83 except template.TemplateDoesNotExist: … … 176 177 177 178 def output_all(form_fields): 178 return ''.join([str(f) for f in form_fields])179 return u''.join([force_unicode(f) for f in form_fields]) 179 180 output_all = register.simple_tag(output_all) 180 181 … … 183 184 for field in auto_pop_fields: 184 185 if change: 185 t.append( 'document.getElementById("id_%s")._changed = true;' % field.name)186 t.append(u'document.getElementById("id_%s")._changed = true;' % field.name) 186 187 else: 187 t.append( 'document.getElementById("id_%s").onchange = function() { this._changed = true; };' % field.name)188 189 add_values = ' + " " + '.join(['document.getElementById("id_%s").value' % g for g in field.prepopulate_from])188 t.append(u'document.getElementById("id_%s").onchange = function() { this._changed = true; };' % field.name) 189 190 add_values = u' + " " + '.join([u'document.getElementById("id_%s").value' % g for g in field.prepopulate_from]) 190 191 for f in field.prepopulate_from: 191 t.append( 'document.getElementById("id_%s").onkeyup = function() {' \192 t.append(u'document.getElementById("id_%s").onkeyup = function() {' \ 192 193 ' var e = document.getElementById("id_%s");' \ 193 194 ' if(!e._changed) { e.value = URLify(%s, %s);} }; ' % ( 194 195 f, field.name, add_values, field.maxlength)) 195 return ''.join(t)196 return u''.join(t) 196 197 auto_populated_field_script = register.simple_tag(auto_populated_field_script) 197 198 … … 199 200 f = bound_field.field 200 201 if f.rel and isinstance(f.rel, models.ManyToManyRel) and f.rel.filter_interface: 201 return '<script type="text/javascript">addEvent(window, "load", function(e) {' \202 return u'<script type="text/javascript">addEvent(window, "load", function(e) {' \ 202 203 ' SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n' % ( 203 204 f.name, f.verbose_name.replace('"', '\\"'), f.rel.filter_interface-1, settings.ADMIN_MEDIA_PREFIX) django/trunk/django/contrib/admin/views/auth.py
r5091 r5609 7 7 from django.http import HttpResponseRedirect 8 8 from django.utils.html import escape 9 from django.utils.translation import ugettext as _ 9 10 10 11 def user_add_stage(request): django/trunk/django/contrib/admin/views/decorators.py
r5091 r5609 4 4 from django.contrib.auth import authenticate, login 5 5 from django.shortcuts import render_to_response 6 from django.utils.translation import gettext_lazy6 from django.utils.translation import ugettext_lazy, ugettext as _ 7 7 import base64, datetime, md5 8 8 import cPickle as pickle 9 9 10 ERROR_MESSAGE = gettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.")10 ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.") 11 11 LOGIN_FORM_KEY = 'this_is_the_login_form' 12 12 django/trunk/django/contrib/admin/views/doc.py
r5302 r5609 10 10 from django.contrib.admin import utils 11 11 from django.contrib.sites.models import Site 12 from django.utils.translation import ugettext as _ 12 13 import inspect, os, re 13 14 django/trunk/django/contrib/admin/views/main.py
r5514 r5609 13 13 from django.utils.html import escape 14 14 from django.utils.text import capfirst, get_text_list 15 from django.utils.encoding import force_unicode, smart_str 16 from django.utils.translation import ugettext as _ 15 17 import operator 16 18 … … 131 133 classes.append('error') 132 134 if classes: 133 self.cell_class_attribute = ' class="%s" ' % ' '.join(classes)135 self.cell_class_attribute = u' class="%s" ' % ' '.join(classes) 134 136 self._repr_filled = False 135 137 136 138 if field.rel: 137 self.related_url = '../../../%s/%s/' % (field.rel.to._meta.app_label, field.rel.to._meta.object_name.lower())139 self.related_url = u'../../../%s/%s/' % (field.rel.to._meta.app_label, field.rel.to._meta.object_name.lower()) 138 140 139 141 def original_value(self): … … 146 148 except AttributeError: 147 149 if isinstance(self.field.rel, models.ManyToOneRel): 148 self._display = getattr(self.original, self.field.name)150 self._display = force_unicode(getattr(self.original, self.field.name), strings_only=True) 149 151 elif isinstance(self.field.rel, models.ManyToManyRel): 150 self._display = ", ".join([str(obj) for obj in getattr(self.original, self.field.name).all()])152 self._display = u", ".join([force_unicode(obj) for obj in getattr(self.original, self.field.name).all()]) 151 153 return self._display 152 154 … … 259 261 new_object = manipulator.save(new_data) 260 262 pk_value = new_object._get_pk_val() 261 LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, str(new_object), ADDITION)262 msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': opts.verbose_name, 'obj': new_object}263 LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, force_unicode(new_object), ADDITION) 264 msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': new_object} 263 265 # Here, we distinguish between different save types by checking for 264 266 # the presence of keys in request.POST. … … 272 274 pk_value = '"%s"' % pk_value.replace('"', '\\"') 273 275 return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, %s, "%s");</script>' % \ 274 (pk_value, str(new_object).replace('"', '\\"')))276 (pk_value, force_unicode(new_object).replace('"', '\\"'))) 275 277 elif "_addanother" in request.POST: 276 request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name))278 request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name))) 277 279 return HttpResponseRedirect(request.path) 278 280 else: … … 292 294 293 295 c = template.RequestContext(request, { 294 'title': _('Add %s') % opts.verbose_name,296 'title': _('Add %s') % force_unicode(opts.verbose_name), 295 297 'form': form, 296 298 'is_popup': '_popup' in request.REQUEST, … … 346 348 if not change_message: 347 349 change_message = _('No fields changed.') 348 LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, str(new_object), CHANGE, change_message)349 350 msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': opts.verbose_name, 'obj': new_object}350 LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, force_unicode(new_object), CHANGE, change_message) 351 352 msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': new_object} 351 353 if "_continue" in request.POST: 352 354 request.user.message_set.create(message=msg + ' ' + _("You may edit it again below.")) … … 356 358 return HttpResponseRedirect(request.path) 357 359 elif "_saveasnew" in request.POST: 358 request.user.message_set.create(message=_('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': opts.verbose_name, 'obj': new_object})360 request.user.message_set.create(message=_('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_unicode(opts.verbose_name), 'obj': new_object}) 359 361 return HttpResponseRedirect("../%s/" % pk_value) 360 362 elif "_addanother" in request.POST: 361 request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name))363 request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name))) 362 364 return HttpResponseRedirect("../add/") 363 365 else: … … 394 396 395 397 c = template.RequestContext(request, { 396 'title': _('Change %s') % opts.verbose_name,398 'title': _('Change %s') % force_unicode(opts.verbose_name), 397 399 'form': form, 398 400 'object_id': object_id, … … 435 437 # Don't display link to edit, because it either has no 436 438 # admin or is edited inline. 437 nh(deleted_objects, current_depth, [ '%s: %s' % (capfirst(related.opts.verbose_name), sub_obj), []])439 nh(deleted_objects, current_depth, [u'%s: %s' % (force_unicode(capfirst(related.opts.verbose_name)), sub_obj), []]) 438 440 else: 439 441 # Display a link to the admin page. 440 nh(deleted_objects, current_depth, [ '%s: <a href="../../../../%s/%s/%s/">%s</a>' % \441 ( capfirst(related.opts.verbose_name), related.opts.app_label, related.opts.object_name.lower(),442 nh(deleted_objects, current_depth, [u'%s: <a href="../../../../%s/%s/%s/">%s</a>' % \ 443 (force_unicode(capfirst(related.opts.verbose_name)), related.opts.app_label, related.opts.object_name.lower(), 442 444 sub_obj._get_pk_val(), sub_obj), []]) 443 445 _get_deleted_objects(deleted_objects, perms_needed, user, sub_obj, related.opts, current_depth+2) … … 449 451 # Don't display link to edit, because it either has no 450 452 # admin or is edited inline. 451 nh(deleted_objects, current_depth, [ '%s: %s' % (capfirst(related.opts.verbose_name), escape(str(sub_obj))), []])453 nh(deleted_objects, current_depth, [u'%s: %s' % (force_unicode(capfirst(related.opts.verbose_name)), escape(sub_obj)), []]) 452 454 else: 453 455 # Display a link to the admin page. 454 nh(deleted_objects, current_depth, [ '%s: <a href="../../../../%s/%s/%s/">%s</a>' % \455 ( capfirst(related.opts.verbose_name), related.opts.app_label, related.opts.object_name.lower(), sub_obj._get_pk_val(), escape(str(sub_obj))), []])456 nh(deleted_objects, current_depth, [u'%s: <a href="../../../../%s/%s/%s/">%s</a>' % \ 457 (force_unicode(capfirst(related.opts.verbose_name)), related.opts.app_label, related.opts.object_name.lower(), sub_obj._get_pk_val(), escape(sub_obj)), []]) 456 458 _get_deleted_objects(deleted_objects, perms_needed, user, sub_obj, related.opts, current_depth+2) 457 459 # If there were related objects, and the user doesn't have … … 467 469 rel_opts_name = related.get_accessor_name() 468 470 has_related_objs = False 469 471 470 472 # related.get_accessor_name() could return None for symmetrical relationships 471 473 if rel_opts_name: … … 480 482 # admin or is edited inline. 481 483 nh(deleted_objects, current_depth, [_('One or more %(fieldname)s in %(name)s: %(obj)s') % \ 482 {'fieldname': related.field.verbose_name, 'name': related.opts.verbose_name, 'obj': escape(str(sub_obj))}, []])484 {'fieldname': force_unicode(related.field.verbose_name), 'name': force_unicode(related.opts.verbose_name), 'obj': escape(sub_obj)}, []]) 483 485 else: 484 486 # Display a link to the admin page. 485 487 nh(deleted_objects, current_depth, [ 486 (_('One or more %(fieldname)s in %(name)s:') % {'fieldname': related.field.verbose_name, 'name':related.opts.verbose_name}) + \487 ( ' <a href="../../../../%s/%s/%s/">%s</a>' % \488 (related.opts.app_label, related.opts.module_name, sub_obj._get_pk_val(), escape(s tr(sub_obj)))), []])488 (_('One or more %(fieldname)s in %(name)s:') % {'fieldname': force_unicode(related.field.verbose_name), 'name': force_unicode(related.opts.verbose_name)}) + \ 489 (u' <a href="../../../../%s/%s/%s/">%s</a>' % \ 490 (related.opts.app_label, related.opts.module_name, sub_obj._get_pk_val(), escape(sub_obj))), []]) 489 491 # If there were related objects, and the user doesn't have 490 492 # permission to change them, add the missing perm to perms_needed. 491 493 if related.opts.admin and has_related_objs: 492 p = '%s.%s' % (related.opts.app_label, related.opts.get_change_permission())494 p = u'%s.%s' % (related.opts.app_label, related.opts.get_change_permission()) 493 495 if not user.has_perm(p): 494 496 perms_needed.add(related.opts.verbose_name) … … 506 508 # Populate deleted_objects, a data structure of all related objects that 507 509 # will also be deleted. 508 deleted_objects = [ '%s: <a href="../../%s/">%s</a>' % (capfirst(opts.verbose_name), object_id, escape(str(obj))), []]510 deleted_objects = [u'%s: <a href="../../%s/">%s</a>' % (force_unicode(capfirst(opts.verbose_name)), force_unicode(object_id), escape(obj)), []] 509 511 perms_needed = set() 510 512 _get_deleted_objects(deleted_objects, perms_needed, request.user, obj, opts, 1) … … 513 515 if perms_needed: 514 516 raise PermissionDenied 515 obj_display = str(obj)517 obj_display = force_unicode(obj) 516 518 obj.delete() 517 519 LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, object_id, obj_display, DELETION) 518 request.user.message_set.create(message=_('The %(name)s "%(obj)s" was deleted successfully.') % {'name': opts.verbose_name, 'obj': obj_display})520 request.user.message_set.create(message=_('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': obj_display}) 519 521 return HttpResponseRedirect("../../") 520 522 extra_context = { 521 523 "title": _("Are you sure?"), 522 "object_name": opts.verbose_name,524 "object_name": force_unicode(opts.verbose_name), 523 525 "object": obj, 524 526 "deleted_objects": deleted_objects, … … 543 545 'title': _('Change history: %s') % obj, 544 546 'action_list': action_list, 545 'module_name': capfirst(model._meta.verbose_name_plural),547 'module_name': force_unicode(capfirst(model._meta.verbose_name_plural)), 546 548 'object': obj, 547 549 } … … 575 577 self.query_set = self.get_query_set() 576 578 self.get_results(request) 577 self.title = (self.is_popup and _('Select %s') % self.opts.verbose_name or _('Select %s to change') % self.opts.verbose_name)579 self.title = (self.is_popup and _('Select %s') % force_unicode(self.opts.verbose_name) or _('Select %s to change') % force_unicode(self.opts.verbose_name)) 578 580 self.filter_specs, self.has_filters = self.get_filters(request) 579 581 self.pk_attname = self.lookup_opts.pk.attname … … 603 605 elif v is not None: 604 606 p[k] = v 605 return '?' + '&'.join([ '%s=%s' % (k, v) for k, v in p.items()]).replace(' ', '%20')607 return '?' + '&'.join([u'%s=%s' % (k, v) for k, v in p.items()]).replace(' ', '%20') 606 608 607 609 def get_results(self, request): … … 689 691 if i in lookup_params: 690 692 del lookup_params[i] 693 for key, value in lookup_params.items(): 694 if not isinstance(key, str): 695 # 'key' will be used as a keyword argument later, so Python 696 # requires it to be a string. 697 del lookup_params[key] 698 lookup_params[smart_str(key)] = value 691 699 692 700 # Apply lookup parameters from the query string. django/trunk/django/contrib/auth/forms.py
r5493 r5609 5 5 from django.core import validators 6 6 from django import oldforms 7 from django.utils.translation import gettext as _7 from django.utils.translation import ugettext as _ 8 8 9 9 class UserCreationForm(oldforms.Manipulator): django/trunk/django/contrib/auth/management.py
r4265 r5609 8 8 9 9 def _get_permission_codename(action, opts): 10 return '%s_%s' % (action, opts.object_name.lower())10 return u'%s_%s' % (action, opts.object_name.lower()) 11 11 12 12 def _get_all_permissions(opts): … … 14 14 perms = [] 15 15 for action in ('add', 'change', 'delete'): 16 perms.append((_get_permission_codename(action, opts), 'Can %s %s' % (action, opts.verbose_name)))16 perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw))) 17 17 return perms + list(opts.permissions) 18 18 django/trunk/django/contrib/auth/models.py
r5590 r5609 3 3 from django.db import backend, connection, models 4 4 from django.contrib.contenttypes.models import ContentType 5 from django.utils.translation import gettext_lazy as _ 5 from django.utils.encoding import smart_str 6 from django.utils.translation import ugettext_lazy as _ 6 7 import datetime 8 import urllib 7 9 8 10 try: … … 19 21 if algo == 'md5': 20 22 import md5 21 return hsh == md5.new(s alt+raw_password).hexdigest()23 return hsh == md5.new(smart_str(salt + raw_password)).hexdigest() 22 24 elif algo == 'sha1': 23 25 import sha 24 return hsh == sha.new(s alt+raw_password).hexdigest()26 return hsh == sha.new(smart_str(salt + raw_password)).hexdigest() 25 27 elif algo == 'crypt': 26 28 try: … … 28 30 except ImportError: 29 31 raise ValueError, "Crypt password algorithm not supported in this environment." 30 return hsh == crypt.crypt( raw_password, salt)32 return hsh == crypt.crypt(smart_str(raw_password), smart_str(salt)) 31 33 raise ValueError, "Got unknown password algorithm type in password." 32 34 … … 57 59 ordering = ('content_type', 'codename') 58 60 59 def __ str__(self):60 return "%s | %s | %s" % (self.content_type.app_label, self.content_type, self.name)61 def __unicode__(self): 62 return u"%s | %s | %s" % (self.content_type.app_label, self.content_type, self.name) 61 63 62 64 class Group(models.Model): … … 78 80 search_fields = ('name',) 79 81 80 def __ str__(self):82 def __unicode__(self): 81 83 return self.name 82 84 … … 134 136 search_fields = ('username', 'first_name', 'last_name', 'email') 135 137 136 def __ str__(self):138 def __unicode__(self): 137 139 return self.username 138 140 139 141 def get_absolute_url(self): 140 return "/users/%s/" % self.username142 return "/users/%s/" % urllib.quote(smart_str(self.username)) 141 143 142 144 def is_anonymous(self): … … 151 153 def get_full_name(self): 152 154 "Returns the first_name plus the last_name, with a space in between." 153 full_name = '%s %s' % (self.first_name, self.last_name)155 full_name = u'%s %s' % (self.first_name, self.last_name) 154 156 return full_name.strip() 155 157 … … 158 160 algo = 'sha1' 159 161 salt = sha.new(str(random.random())).hexdigest()[:5] 160 hsh = sha.new(salt +raw_password).hexdigest()162 hsh = sha.new(salt + smart_str(raw_password)).hexdigest() 161 163 self.password = '%s$%s$%s' % (algo, salt, hsh) 162 164 … … 170 172 if '$' not in self.password: 171 173 import md5 172 is_correct = (self.password == md5.new( raw_password).hexdigest())174 is_correct = (self.password == md5.new(smart_str(raw_password)).hexdigest()) 173 175 if is_correct: 174 176 # Convert the password to the new, more secure format. … … 210 212 def get_all_permissions(self): 211 213 if not hasattr(self, '_perm_cache'): 212 self._perm_cache = set([ "%s.%s" % (p.content_type.app_label, p.codename) for p in self.user_permissions.select_related()])214 self._perm_cache = set([u"%s.%s" % (p.content_type.app_label, p.codename) for p in self.user_permissions.select_related()]) 213 215 self._perm_cache.update(self.get_group_permissions()) 214 216 return self._perm_cache … … 272 274 message = models.TextField(_('message')) 273 275 274 def __ str__(self):276 def __unicode__(self): 275 277 return self.message 276 278 … … 282 284 pass 283 285 286 def __unicode__(self): 287 return 'AnonymousUser' 288 284 289 def __str__(self): 285 return 'AnonymousUser'290 return unicode(self).encode('utf-8') 286 291 287 292 def __eq__(self, other): django/trunk/django/contrib/auth/views.py
r5072 r5609 8 8 from django.contrib.auth.decorators import login_required 9 9 from django.contrib.auth import REDIRECT_FIELD_NAME 10 from django.utils.translation import ugettext as _ 10 11 11 12 def login(request, template_name='registration/login.html'): django/trunk/django/contrib/comments/feeds.py
r5408 r5609 12 12 if not hasattr(self, '_site'): 13 13 self._site = Site.objects.get_current() 14 return "%s comments" % self._site.name14 return u"%s comments" % self._site.name 15 15 16 16 def link(self): … … 22 22 if not hasattr(self, '_site'): 23 23 self._site = Site.objects.get_current() 24 return "Latest comments on %s" % self._site.name24 return u"Latest comments on %s" % self._site.name 25 25 26 26 def get_query_set(self): django/trunk/django/contrib/comments/models.py
r4873 r5609 3 3 from django.contrib.sites.models import Site 4 4 from django.contrib.auth.models import User 5 from django.utils.translation import gettext_lazy as _5 from django.utils.translation import ugettext_lazy as _ 6 6 from django.conf import settings 7 7 import datetime django/trunk/django/contrib/comments/views/comments.py
r5091 r5609 12 12 from django.utils.text import normalize_newlines 13 13 from django.conf import settings 14 from django.utils.translation import ngettext 14 from django.utils.translation import ungettext, ugettext as _ 15 from django.utils.encoding import smart_unicode 15 16 import base64, datetime 16 17 … … 109 110 # send the comment to the managers. 110 111 if self.user_cache.comment_set.count() <= settings.COMMENTS_FIRST_FEW: 111 message = ngettext('This comment was posted by a user who has posted fewer than %(count)s comment:\n\n%(text)s',112 message = ungettext('This comment was posted by a user who has posted fewer than %(count)s comment:\n\n%(text)s', 112 113 'This comment was posted by a user who has posted fewer than %(count)s comments:\n\n%(text)s', settings.COMMENTS_FIRST_FEW) % \ 113 114 {'count': settings.COMMENTS_FIRST_FEW, 'text': c.get_as_text()} … … 249 250 # serve up the "Thanks for posting" page as if the comment WAS posted. 250 251 if request.META['REMOTE_ADDR'] in settings.BANNED_IPS: 251 mail_admins("Banned IP attempted to post comment", s tr(request.POST) + "\n\n" + str(request.META))252 mail_admins("Banned IP attempted to post comment", smart_unicode(request.POST) + "\n\n" + str(request.META)) 252 253 else: 253 254 manipulator.do_html2python(new_data) … … 313 314 if request.META['REMOTE_ADDR'] in settings.BANNED_IPS: 314 315 from django.core.mail import mail_admins 315 mail_admins("Practical joker", s tr(request.POST) + "\n\n" + str(request.META))316 mail_admins("Practical joker", smart_unicode(request.POST) + "\n\n" + str(request.META)) 316 317 else: 317 318 manipulator.do_html2python(new_data) django/trunk/django/contrib/comments/views/karma.py
r4486 r5609 3 3 from django.template import RequestContext 4 4 from django.contrib.comments.models import Comment, KarmaScore 5 from django.utils.translation import ugettext as _ 5 6 6 7 def vote(request, comment_id, vote): django/trunk/django/contrib/contenttypes/generic.py
r5172 r5609 50 50 def __get__(self, instance, instance_type=None): 51 51 if instance is None: 52 raise AttributeError, "%s must be accessed via instance" % self.name52 raise AttributeError, u"%s must be accessed via instance" % self.name 53 53 54 54 try: … … 67 67 def __set__(self, instance, value): 68 68 if instance is None: 69 raise AttributeError, "%s must be accessed via instance" % self.related.opts.object_name69 raise AttributeError, u"%s must be accessed via instance" % self.related.opts.object_name 70 70 71 71 ct = None django/trunk/django/contrib/contenttypes/management.py
r4703 r5609 5 5 from django.dispatch import dispatcher 6 6 from django.db.models import get_apps, get_models, signals 7 from django.utils.encoding import smart_unicode 7 8 8 9 def create_contenttypes(app, created_models, verbosity=2): … … 18 19 model=opts.object_name.lower()) 19 20 except ContentType.DoesNotExist: 20 ct = ContentType(name=s tr(opts.verbose_name),21 ct = ContentType(name=smart_unicode(opts.verbose_name_raw), 21 22 app_label=opts.app_label, model=opts.object_name.lower()) 22 23 ct.save() django/trunk/django/contrib/contenttypes/models.py
r4703 r5609 1 1 from django.db import models 2 from django.utils.translation import gettext_lazy as _ 2 from django.utils.translation import ugettext_lazy as _ 3 from django.utils.encoding import smart_unicode 3 4 4 5 CONTENT_TYPE_CACHE = {} … … 14 15 ct = CONTENT_TYPE_CACHE[key] 15 16 except KeyError: 16 # The s tr() is needed around opts.verbose_name because it's a17 # django.utils.functional.__proxy__ object.17 # The smart_unicode() is needed around opts.verbose_name_raw because it might 18 # be a django.utils.functional.__proxy__ object. 18 19 ct, created = self.model._default_manager.get_or_create(app_label=key[0], 19 model=key[1], defaults={'name': s tr(opts.verbose_name)})20 model=key[1], defaults={'name': smart_unicode(opts.verbose_name_raw)}) 20 21 CONTENT_TYPE_CACHE[key] = ct 21 22 return ct 22 23 23 24 def clear_cache(self): 24 25 """ … … 43 44 unique_together = (('app_label', 'model'),) 44 45 45 def __ str__(self):46 def __unicode__(self): 46 47 return self.name 47 48 django/trunk/django/contrib/databrowse/datastructures.py
r5016 r5609 8 8 from django.utils.text import capfirst 9 9 from django.utils.translation import get_date_formats 10 from django.utils.encoding import smart_unicode, smart_str, iri_to_uri 10 11 11 12 EMPTY_VALUE = '(None)' … … 20 21 21 22 def __repr__(self): 22 return '<EasyModel for %s>' % s elf.model._meta.object_name23 return '<EasyModel for %s>' % smart_str(self.model._meta.object_name) 23 24 24 25 def model_databrowse(self): … … 55 56 56 57 def __repr__(self): 57 return '<EasyField for %s.%s>' % (self.model.model._meta.object_name, self.field.name)58 return smart_str(u'<EasyField for %s.%s>' % (self.model.model._meta.object_name, self.field.name)) 58 59 59 60 def choices(self): … … 73 74 74 75 def __repr__(self): 75 return '<EasyChoice for %s.%s>' % (self.model.model._meta.object_name, self.field.name)76 return smart_str(u'<EasyChoice for %s.%s>' % (self.model.model._meta.object_name, self.field.name)) 76 77 77 78 def url(self): 78 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, self.value)79 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)) 79 80 80 81 class EasyInstance(object): … … 83 84 84 85 def __repr__(self): 85 return '<EasyInstance for %s (%s)>' % (self.model.model._meta.object_name, self.instance._get_pk_val()) 86 return smart_str(u'<EasyInstance for %s (%s)>' % (self.model.model._meta.object_name, self.instance._get_pk_val())) 87 88 def __unicode__(self): 89 val = smart_unicode(self.instance) 90 if len(val) > 30: 91 return val[:30] + u'...' 92 return val 86 93 87 94 def __str__(self): 88 val = str(self.instance) 89 if len(val) > 30: 90 return val[:30] + '...' 91 return val 95 return self.__unicode__().encode('utf-8') 92 96 93 97 def pk(self): … … 95 99 96 100 def url(self): 97 return '%s%s/%s/objects/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.pk())101 return '%s%s/%s/objects/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, iri_to_uri(self.pk())) 98 102 99 103 def fields(self): … … 127 131 128 132 def __repr__(self): 129 return '<EasyInstanceField for %s.%s>' % (self.model.model._meta.object_name, self.field.name)133 return smart_str(u'<EasyInstanceField for %s.%s>' % (self.model.model._meta.object_name, self.field.name)) 130 134 131 135 def values(self): … … 176 180 lst = [] 177 181 for value in self.values(): 178 url = '%s%s/%s/objects/%s/' % (self.model.site.root_url, m.model._meta.app_label, m.model._meta.module_name, value._get_pk_val())179 lst.append((s tr(value), url))182 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())) 183 lst.append((smart_unicode(value), url)) 180 184 else: 181 185 lst = [(value, None) for value in self.values()] … … 183 187 lst = [] 184 188 for value in self.values(): 185 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, self.raw_value)189 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)) 186 190 lst.append((value, url)) 187 191 elif isinstance(self.field, models.URLField): 188 192 val = self.values()[0] 189 lst = [(val, val)]193 lst = [(val, iri_to_uri(val))] 190 194 else: 191 195 lst = [(self.values()[0], None)] django/trunk/django/contrib/databrowse/plugins/calendars.py
r5011 r5609 7 7 from django.utils.translation import get_date_formats 8 8 from django.views.generic import date_based 9 from django.utils.encoding import force_unicode 9 10 import datetime 10 11 import time … … 28 29 fields = self.field_dict(model) 29 30 if not fields: 30 return ''31 return '<p class="filter"><strong>View calendar by:</strong> %s</p>' % \32 ', '.join(['<a href="calendars/%s/">%s</a>' % (f.name, capfirst(f.verbose_name)) for f in fields.values()])31 return u'' 32 return u'<p class="filter"><strong>View calendar by:</strong> %s</p>' % \ 33 u', '.join(['<a href="calendars/%s/">%s</a>' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()]) 33 34 34 35 def urls(self, plugin_name, easy_instance_field): 35 36 if isinstance(easy_instance_field.field, models.DateField): 36 return [ '%s%s/%s/%s/%s/%s/' % (easy_instance_field.model.url(),37 return [u'%s%s/%s/%s/%s/%s/' % (easy_instance_field.model.url(), 37 38 plugin_name, easy_instance_field.field.name, 38 39 easy_instance_field.raw_value.year, django/trunk/django/contrib/databrowse/plugins/fieldchoices.py
r5011 r5609 5 5 from django.shortcuts import render_to_response 6 6 from django.utils.text import capfirst 7 from django.utils.encoding import smart_str, force_unicode 7 8 from django.views.generic import date_based 8 9 import datetime 9 10 import time 11 import urllib 10 12 11 13 class FieldChoicePlugin(DatabrowsePlugin): … … 30 32 fields = self.field_dict(model) 31 33 if not fields: 32 return ''33 return '<p class="filter"><strong>View by:</strong> %s</p>' % \34 ', '.join(['<a href="fields/%s/">%s</a>' % (f.name, capfirst(f.verbose_name)) for f in fields.values()])34 return u'' 35 return u'<p class="filter"><strong>View by:</strong> %s</p>' % \ 36 u', '.join(['<a href="fields/%s/">%s</a>' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()]) 35 37 36 38 def urls(self, plugin_name, easy_instance_field): 37 39 if easy_instance_field.field in self.field_dict(easy_instance_field.model.model).values(): 38 return [ '%s%s/%s/%s/' % (easy_instance_field.model.url(),40 return [u'%s%s/%s/%s/' % (easy_instance_field.model.url(), 39 41 plugin_name, easy_instance_field.field.name, 40 easy_instance_field.raw_value)]42 urllib.quote(smart_str(easy_instance_field.raw_value)))] 41 43 42 44 def model_view(self, request, model_databrowse, url): django/trunk/django/contrib/databrowse/sites.py
r5011 r5609 61 61 def main_view(self, request): 62 62 easy_model = EasyModel(self.site, self.model) 63 html_snippets = '\n'.join([p.model_index_html(request, self.model, self.site) for p in self.plugins.values()])63 html_snippets = u'\n'.join([p.model_index_html(request, self.model, self.site) for p in self.plugins.values()]) 64 64 return render_to_response('databrowse/model_detail.html', { 65 65 'model': easy_model, django/trunk/django/contrib/databrowse/templates/databrowse/fieldchoice_list.html
r5011 r5609 11 11 <ul class="objectlist"> 12 12 {% for object in object_list %} 13 <li class="{% cycle odd,even %}"><a href="{{ object }}/">{{ object|escape }}</a></li>13 <li class="{% cycle odd,even %}"><a href="{{ object|iriencode }}/">{{ object|escape }}</a></li> 14 14 {% endfor %} 15 15 </ul> django/trunk/django/contrib/flatpages/models.py
r4849 r5609 2 2 from django.db import models 3 3 from django.contrib.sites.models import Site 4 from django.utils.translation import gettext_lazy as _4 from django.utils.translation import ugettext_lazy as _ 5 5 6 6 class FlatPage(models.Model): … … 27 27 search_fields = ('url', 'title') 28 28 29 def __ str__(self):30 return "%s -- %s" % (self.url, self.title)29 def __unicode__(self): 30 return u"%s -- %s" % (self.url, self.title) 31 31 32 32 def get_absolute_url(self): django/trunk/django/contrib/humanize/templatetags/humanize.py
r4856 r5609 1 from django.utils.translation import ngettext2 from django.utils. translation import gettext_lazy as _1 from django.utils.translation import ungettext, ugettext as _ 2 from django.utils.encoding import force_unicode 3 3 from django import template 4 4 import re … … 17 17 t = (_('th'), _('st'), _('nd'), _('rd'), _('th'), _('th'), _('th'), _('th'), _('th'), _('th')) 18 18 if value % 100 in (11, 12, 13): # special case 19 return "%d%s" % (value, t[0])20 return '%d%s' % (value, t[value % 10])19 return u"%d%s" % (value, t[0]) 20 return u'%d%s' % (value, t[value % 10]) 21 21 register.filter(ordinal) 22 22 … … 26 26 For example, 3000 becomes '3,000' and 45000 becomes '45,000'. 27 27 """ 28 orig = str(value)29 new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', str(value))28 orig = force_unicode(value) 29 new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig) 30 30 if orig == new: 31 31 return new … … 45 45 if value < 1000000000: 46 46 new_value = value / 1000000.0 47 return ngettext('%(value).1f million', '%(value).1f million', new_value) % {'value': new_value}47 return ungettext('%(value).1f million', '%(value).1f million', new_value) % {'value': new_value} 48 48 if value < 1000000000000: 49 49 new_value = value / 1000000000.0 50 return ngettext('%(value).1f billion', '%(value).1f billion', new_value) % {'value': new_value}50 return ungettext('%(value).1f billion', '%(value).1f billion', new_value) % {'value': new_value} 51 51 if value < 1000000000000000: 52 52 new_value = value / 1000000000000.0 53 return ngettext('%(value).1f trillion', '%(value).1f trillion', new_value) % {'value': new_value}53 return ungettext('%(value).1f trillion', '%(value).1f trillion', new_value) % {'value': new_value} 54 54 return value 55 55 register.filter(intword) django/trunk/django/contrib/localflavor/au/forms.py
r4955 r5609 6 6 from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES 7 7 from django.newforms.util import smart_unicode 8 from django.utils.translation import gettext8 from django.utils.translation import ugettext 9 9 import re 10 10 … … 16 16 super(AUPostCodeField, self).__init__(r'^\d{4}$', 17 17 max_length=None, min_length=None, 18 error_message= gettext(u'Enter a 4 digit post code.'),19 *args, **kwargs)18 error_message=ugettext('Enter a 4 digit post code.'), 19 *args, **kwargs) 20 20 21 21 class AUPhoneNumberField(Field): 22 22 """Australian phone number field.""" 23 23 def clean(self, value): 24 """ Validate a phone number. Strips parentheses, whitespace and25 hyphens.24 """ 25 Validate a phone number. Strips parentheses, whitespace and hyphens. 26 26 """ 27 27 super(AUPhoneNumberField, self).clean(value) … … 40 40 """ 41 41 def __init__(self, attrs=None): 42 from au_states import STATE_CHOICES # relative import42 from au_states import STATE_CHOICES 43 43 super(AUStateSelect, self).__init__(attrs, choices=STATE_CHOICES) django/trunk/django/contrib/localflavor/br/forms.py
r5099 r5609 7 7 from django.newforms.fields import Field, RegexField, CharField, Select, EMPTY_VALUES 8 8 from django.utils.encoding import smart_unicode 9 from django.utils.translation import gettext9 from django.utils.translation import ugettext 10 10 import re 11 11 … … 16 16 super(BRZipCodeField, self).__init__(r'^\d{5}-\d{3}$', 17 17 max_length=None, min_length=None, 18 error_message= gettext('Enter a zip code in the format XXXXX-XXX.'),19 *args, **kwargs)18 error_message=ugettext('Enter a zip code in the format XXXXX-XXX.'), 19 *args, **kwargs) 20 20 21 21 class BRPhoneNumberField(Field): … … 28 28 if m: 29 29 return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) 30 raise ValidationError( gettext(u'Phone numbers must be in XX-XXXX-XXXX format.'))30 raise ValidationError(ugettext('Phone numbers must be in XX-XXXX-XXXX format.')) 31 31 32 32 class BRStateSelect(Select): … … 36 36 """ 37 37 def __init__(self, attrs=None): 38 from br_states import STATE_CHOICES # relative import38 from br_states import STATE_CHOICES 39 39 super(BRStateSelect, self).__init__(attrs, choices=STATE_CHOICES) 40 40 … … 70 70 int(value) 71 71 except ValueError: 72 raise ValidationError( gettext("This field requires only numbers."))72 raise ValidationError(ugettext("This field requires only numbers.")) 73 73 if len(value) != 11: 74 raise ValidationError( gettext("This field requires at most 11 digits or 14 characters."))74 raise ValidationError(ugettext("This field requires at most 11 digits or 14 characters.")) 75 75 orig_dv = value[-2:] 76 76 … … 82 82 value = value[:-1] + str(new_2dv) 83 83 if value[-2:] != orig_dv: 84 raise ValidationError( gettext("Invalid CPF number."))84 raise ValidationError(ugettext("Invalid CPF number.")) 85 85 86 86 return orig_value … … 104 104 if len(value) != 14: 105 105 raise ValidationError( 106 gettext("This field requires at least 14 digits"))106 ugettext("This field requires at least 14 digits")) 107 107 orig_dv = value[-2:] 108 108 … … 114 114 value = value[:-1] + str(new_2dv) 115 115 if value[-2:] != orig_dv: 116 raise ValidationError( gettext("Invalid CNPJ number."))116 raise ValidationError(ugettext("Invalid CNPJ number.")) 117 117 118 118 return orig_value django/trunk/django/contrib/localflavor/ch/ch_states.py
r5132 r5609 1 1 # -*- coding: utf-8 -* 2 from django.utils.translation import gettext_lazy as _2 from django.utils.translation import ugettext_lazy as _ 3 3 4 4 STATE_CHOICES = ( django/trunk/django/contrib/localflavor/ch/forms.py
r5132 r5609 6 6 from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES 7 7 from django.utils.encoding import smart_unicode 8 from django.utils.translation import gettext8 from django.utils.translation import ugettext 9 9 import re 10 10 … … 16 16 super(CHZipCodeField, self).__init__(r'^\d{4}$', 17 17 max_length=None, min_length=None, 18 error_message= gettext('Enter a zip code in the format XXXX.'),18 error_message=ugettext('Enter a zip code in the format XXXX.'), 19 19 *args, **kwargs) 20 20 … … 88 88 def clean(self, value): 89 89 super(CHIdentityCardNumberField, self).clean(value) 90 error_msg = gettext('Enter a valid Swiss identity or passport card number in X1234567<0 or 1234567890 format.')90 error_msg = ugettext('Enter a valid Swiss identity or passport card number in X1234567<0 or 1234567890 format.') 91 91 if value in EMPTY_VALUES: 92 92 return u'' django/trunk/django/contrib/localflavor/cl/forms.py
r5098 r5609 5 5 from django.newforms import ValidationError 6 6 from django.newforms.fields import RegexField, EMPTY_VALUES 7 from django.utils.translation import gettext 7 from django.utils.translation import ugettext 8 from django.utils.encoding import smart_unicode 8 9 9 10 class CLRutField(RegexField): … … 19 20 del kwargs['strict'] 20 21 super(CLRutField, self).__init__(r'^(\d{1,2}\.)?\d{3}\.\d{3}-[\dkK]$', 21 error_message= gettext('Enter valid a Chilean RUT. The format is XX.XXX.XXX-X.'),22 *args, **kwargs)22 error_message=ugettext('Enter valid a Chilean RUT. The format is XX.XXX.XXX-X.'), 23 *args, **kwargs) 23 24 else: 24 25 # In non-strict mode, accept RUTs that validate but do not exist in 25 26 # the real world. 26 super(CLRutField, self).__init__(r'^[\d\.]{1,11}-?[\dkK]$', error_message= gettext(u'Enter valid a Chilean RUT'), *args, **kwargs)27 super(CLRutField, self).__init__(r'^[\d\.]{1,11}-?[\dkK]$', error_message=ugettext('Enter valid a Chilean RUT'), *args, **kwargs) 27 28 28 29 def clean(self, value): … … 50 51 if multi == 8: 51 52 multi = 2 52 return '0123456789K0'[11 - suma % 11]53 return u'0123456789K0'[11 - suma % 11] 53 54 54 55 def _canonify(self, rut): … … 57 58 tuple. 58 59 """ 59 rut = s tr(rut).replace(' ', '').replace('.', '').replace('-', '')60 rut = smart_unicode(rut).replace(' ', '').replace('.', '').replace('-', '') 60 61 return rut[:-1], rut[-1] 61 62 … … 75 76 new_dot = pos - 3 76 77 code = code[:new_dot] + '.' + code[new_dot:] 77 return '%s-%s' % (code, verifier)78 return u'%s-%s' % (code, verifier) 78 79 django/trunk/django/contrib/localflavor/de/de_states.py
r4926 r5609 1 1 # -*- coding: utf-8 -* 2 from django.utils.translation import gettext_lazy as _2 from django.utils.translation import ugettext_lazy as _ 3 3 4 4 STATE_CHOICES = ( django/trunk/django/contrib/localflavor/de/forms.py
r4939 r5609 5 5 from django.newforms import ValidationError 6 6 from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES 7 from django.utils.translation import gettext7 from django.utils.translation import ugettext 8 8 import re 9 9 … … 14 14 super(DEZipCodeField, self).__init__(r'^\d{5}$', 15 15 max_length=None, min_length=None, 16 error_message= gettext(u'Enter a zip code in the format XXXXX.'),17 *args, **kwargs)16 error_message=ugettext('Enter a zip code in the format XXXXX.'), 17 *args, **kwargs) 18 18 19 19 class DEStateSelect(Select): … … 22 22 """ 23 23 def __init__(self, attrs=None): 24 from de_states import STATE_CHOICES # relative import24 from de_states import STATE_CHOICES 25 25 super(DEStateSelect, self).__init__(attrs, choices=STATE_CHOICES) 26 26 … … 58 58 def clean(self, value): 59 59 super(DEIdentityCardNumberField, self).clean(value) 60 error_msg = gettext(u'Enter a valid German identity card number in XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format.')60 error_msg = ugettext('Enter a valid German identity card number in XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format.') 61 61 if value in EMPTY_VALUES: 62 62 return u'' … … 72 72 raise ValidationError(error_msg) 73 73 74 all_digits = "%s%s%s%s" % (residence, birthday, validity, checksum)74 all_digits = u"%s%s%s%s" % (residence, birthday, validity, checksum) 75 75 if not self.has_valid_checksum(residence) or not self.has_valid_checksum(birthday) or \ 76 76 not self.has_valid_checksum(validity) or not self.has_valid_checksum(all_digits): django/trunk/django/contrib/localflavor/fi/forms.py
r4970 r5609 6 6 from django.newforms import ValidationError 7 7 from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES 8 from django.utils.translation import gettext8 from django.utils.translation import ugettext 9 9 10 10 class FIZipCodeField(RegexField): … … 12 12 super(FIZipCodeField, self).__init__(r'^\d{5}$', 13 13 max_length=None, min_length=None, 14 error_message= gettext(u'Enter a zip code in the format XXXXX.'),15 *args, **kwargs)14 error_message=ugettext('Enter a zip code in the format XXXXX.'), 15 *args, **kwargs) 16 16 17 17 class FIMunicipalitySelect(Select): … … 20 20 """ 21 21 def __init__(self, attrs=None): 22 from fi_municipalities import MUNICIPALITY_CHOICES # relative import22 from fi_municipalities import MUNICIPALITY_CHOICES 23 23 super(FIMunicipalitySelect, self).__init__(attrs, choices=MUNICIPALITY_CHOICES) 24 24 … … 38 38 (?P<checksum>[%s])$""" % checkmarks, value, re.VERBOSE | re.IGNORECASE) 39 39 if not result: 40 raise ValidationError( gettext(u'Enter a valid Finnish social security number.'))40 raise ValidationError(ugettext('Enter a valid Finnish social security number.')) 41 41 gd = result.groupdict() 42 42 checksum = int(gd['date'] + gd['serial']) 43 43 if checkmarks[checksum % len(checkmarks)] == gd['checksum'].upper(): 44 44 return u'%s' % value.upper() 45 raise ValidationError( gettext(u'Enter a valid Finnish social security number.'))45 raise ValidationError(ugettext('Enter a valid Finnish social security number.')) django/trunk/django/contrib/localflavor/fr/forms.py
r4918 r5609 6 6 from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES 7 7 from django.utils.encoding import smart_unicode 8 from django.utils.translation import gettext8 from django.utils.translation import ugettext 9 9 import re 10 10 … … 15 15 super(FRZipCodeField, self).__init__(r'^\d{5}$', 16 16 max_length=None, min_length=None, 17 error_message= gettext(u'Enter a zip code in the format XXXXX.'),18 *args, **kwargs)17 error_message=ugettext('Enter a zip code in the format XXXXX.'), 18 *args, **kwargs) 19 19 20 20 class FRPhoneNumberField(Field): … … 40 40 """ 41 41 def __init__(self, attrs=None): 42 from fr_department import DEPARTMENT_ASCII_CHOICES # relative import42 from fr_department import DEPARTMENT_ASCII_CHOICES 43 43 super(FRDepartmentSelect, self).__init__(attrs, choices=DEPARTMENT_ASCII_CHOICES) 44 44 django/trunk/django/contrib/localflavor/is_/forms.py
r5210 r5609 6 6 from django.newforms.fields import RegexField, EMPTY_VALUES 7 7 from django.newforms.widgets import Select 8 from django.utils.translation import gettext 8 from django.utils.translation import ugettext 9 from django.utils.encoding import smart_unicode 9 10 10 11 class ISIdNumberField(RegexField): … … 14 15 """ 15 16 def __init__(self, *args, **kwargs): 16 error_msg = gettext(u'Enter a valid Icelandic identification number. The format is XXXXXX-XXXX.')17 error_msg = ugettext('Enter a valid Icelandic identification number. The format is XXXXXX-XXXX.') 17 18 kwargs['min_length'],kwargs['max_length'] = 10,11 18 19 super(ISIdNumberField, self).__init__(r'^\d{6}(-| )?\d{4}$', error_message=error_msg, *args, **kwargs) … … 28 29 return self._format(value) 29 30 else: 30 raise ValidationError( gettext(u'The Icelandic identification number is not valid.'))31 raise ValidationError(ugettext(u'The Icelandic identification number is not valid.')) 31 32 32 33 def _canonify(self, value): … … 49 50 display format. 50 51 """ 51 return value[:6]+'-'+value[6:]52 return smart_unicode(value[:6]+'-'+value[6:]) 52 53 53 54 class ISPhoneNumberField(RegexField): django/trunk/django/contrib/localflavor/it/forms.py
r5018 r5609 5 5 from django.newforms import ValidationError 6 6 from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES 7 from django.utils.translation import gettext7 from django.utils.translation import ugettext 8 8 from django.utils.encoding import smart_unicode 9 9 from django.contrib.localflavor.it.util import ssn_check_digit, vat_number_check_digit … … 14 14 super(ITZipCodeField, self).__init__(r'^\d{5}$', 15 15 max_length=None, min_length=None, 16 error_message= gettext(u'Enter a valid zip code.'),17 *args, **kwargs)16 error_message=ugettext('Enter a valid zip code.'), 17 *args, **kwargs) 18 18 19 19 class ITRegionSelect(Select): … … 22 22 """ 23 23 def __init__(self, attrs=None): 24 from it_region import REGION_CHOICES # relative import24 from it_region import REGION_CHOICES 25 25 super(ITRegionSelect, self).__init__(attrs, choices=REGION_CHOICES) 26 26 … … 30 30 """ 31 31 def __init__(self, attrs=None): 32 from it_province import PROVINCE_CHOICES # relative import32 from it_province import PROVINCE_CHOICES 33 33 super(ITProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES) 34 34 … … 39 39 'Informazioni sulla codificazione delle persone fisiche'. 40 40 """ 41 err_msg = gettext(u'Enter a valid Social Security number.')41 err_msg = ugettext(u'Enter a valid Social Security number.') 42 42 def __init__(self, *args, **kwargs): 43 43 super(ITSocialSecurityNumberField, self).__init__(r'^\w{3}\s*\w{3}\s*\w{5}\s*\w{5}$', … … 66 66 if value == u'': 67 67 return value 68 err_msg = gettext(u'Enter a valid VAT number.')68 err_msg = ugettext(u'Enter a valid VAT number.') 69 69 try: 70 70 vat_number = int(value) django/trunk/django/contrib/localflavor/it/it_province.py
r4862 r5609 34 34 ('CN', 'Cuneo'), 35 35 ('EN', 'Enna'), 36 # ('FM', 'Fermo'), # active starting from 2009 36 # ('FM', 'Fermo'), # active starting from 2009 37 37 ('FE', 'Ferrara'), 38 38 ('FI', 'Firenze'), django/trunk/django/contrib/localflavor/it/util.py
r5018 r5609 1 from django.utils.encoding import smart_str, smart_unicode 2 1 3 def ssn_check_digit(value): 2 4 "Calculate Italian social security number check digit." 3 5 ssn_even_chars = { 4 '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 5 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 6 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 7 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25 6 '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, 7 '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 8 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 9 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 10 'Y': 24, 'Z': 25 8 11 } 9 12 ssn_odd_chars = { 10 '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8': 19, '9': 21, 11 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15, 'H': 17, 'I': 19, 'J': 21, 12 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11, 'P': 3, 'Q': 6, 'R': 8, 'S': 12, 13 'T': 14, 'U': 16, 'V': 10, 'W': 22, 'X': 25, 'Y': 24, 'Z': 23 13 '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8': 14 19, '9': 21, 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15, 15 'H': 17, 'I': 19, 'J': 21, 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11, 16 'P': 3, 'Q': 6, 'R': 8, 'S': 12, 'T': 14, 'U': 16, 'V': 10, 'W': 22, 17 'X': 25, 'Y': 24, 'Z': 23 14 18 } 15 19 # Chars from 'A' to 'Z' … … 18 22 ssn = value.upper() 19 23 total = 0 20 for i in range(0, 15):24 for i in range(0, 15): 21 25 try: 22 26 if i % 2 == 0: … … 31 35 def vat_number_check_digit(vat_number): 32 36 "Calculate Italian VAT number check digit." 33 normalized_vat_number = s tr(vat_number).zfill(10)37 normalized_vat_number = smart_str(vat_number).zfill(10) 34 38 total = 0 35 39 for i in range(0, 10, 2): … … 38 42 quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, 10) 39 43 total += quotient + remainder 40 return s tr((10 - total % 10) % 10)44 return smart_unicode((10 - total % 10) % 10) django/trunk/django/contrib/localflavor/jp/forms.py
r4822 r5609 5 5 from django.core import validators 6 6 from django.newforms import ValidationError 7 from django.utils.translation import gettext7 from django.utils.translation import ugettext 8 8 from django.newforms.fields import RegexField, Select 9 9 … … 19 19 super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$', 20 20 max_length=None, min_length=None, 21 error_message= gettext(u'Enter a postal code in the format XXXXXXX or XXX-XXXX.'),22 *args, **kwargs)21 error_message=ugettext('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), 22 *args, **kwargs) 23 23 24 24 def clean(self, value): django/trunk/django/contrib/localflavor/jp/jp_prefectures.py
r4822 r5609 1 from django.utils.translation import gettext_lazy asgettext_lazy1 from django.utils.translation import ugettext_lazy 2 2 3 3 JP_PREFECTURES = ( 4 ('hokkaido', gettext_lazy('Hokkaido'),),5 ('aomori', gettext_lazy('Aomori'),),6 ('iwate', gettext_lazy('Iwate'),),7 ('miyagi', gettext_lazy('Miyagi'),),8 ('akita', gettext_lazy('Akita'),),9 ('yamagata', gettext_lazy('Yamagata'),),10 ('fukushima', gettext_lazy('Fukushima'),),11 ('ibaraki', gettext_lazy('Ibaraki'),),12 ('tochigi', gettext_lazy('Tochigi'),),13 ('gunma', gettext_lazy('Gunma'),),14 ('saitama', gettext_lazy('Saitama'),),15 ('chiba', gettext_lazy('Chiba'),),16 ('tokyo', gettext_lazy('Tokyo'),),17 ('kanagawa', gettext_lazy('Kanagawa'),),18 ('yamanashi', gettext_lazy('Yamanashi'),),19 ('nagano', gettext_lazy('Nagano'),),20 ('niigata', gettext_lazy('Niigata'),),21 ('toyama', gettext_lazy('Toyama'),),22 ('ishikawa', gettext_lazy('Ishikawa'),),23 ('fukui', gettext_lazy('Fukui'),),24 ('gifu', gettext_lazy('Gifu'),),25 ('shizuoka', gettext_lazy('Shizuoka'),),26 ('aichi', gettext_lazy('Aichi'),),27 ('mie', gettext_lazy('Mie'),),28 ('shiga', gettext_lazy('Shiga'),),29 ('kyoto', gettext_lazy('Kyoto'),),30 ('osaka', gettext_lazy('Osaka'),),31 ('hyogo', gettext_lazy('Hyogo'),),32 ('nara', gettext_lazy('Nara'),),33 ('wakayama', gettext_lazy('Wakayama'),),34 ('tottori', gettext_lazy('Tottori'),),35 ('shimane', gettext_lazy('Shimane'),),36 ('okayama', gettext_lazy('Okayama'),),37 ('hiroshima', gettext_lazy('Hiroshima'),),38 ('yamaguchi', gettext_lazy('Yamaguchi'),),39 ('tokushima', gettext_lazy('Tokushima'),),40 ('kagawa', gettext_lazy('Kagawa'),),41 ('ehime', gettext_lazy('Ehime'),),42 ('kochi', gettext_lazy('Kochi'),),43 ('fukuoka', gettext_lazy('Fukuoka'),),44 ('saga', gettext_lazy('Saga'),),45 ('nagasaki', gettext_lazy('Nagasaki'),),46 ('kumamoto', gettext_lazy('Kumamoto'),),47 ('oita', gettext_lazy('Oita'),),48 ('miyazaki', gettext_lazy('Miyazaki'),),49 ('kagoshima', gettext_lazy('Kagoshima'),),50 ('okinawa', gettext_lazy('Okinawa'),),4 ('hokkaido', ugettext_lazy('Hokkaido'),), 5 ('aomori', ugettext_lazy('Aomori'),), 6 ('iwate', ugettext_lazy('Iwate'),), 7 ('miyagi', ugettext_lazy('Miyagi'),), 8 ('akita', ugettext_lazy('Akita'),), 9 ('yamagata', ugettext_lazy('Yamagata'),), 10 ('fukushima', ugettext_lazy('Fukushima'),), 11 ('ibaraki', ugettext_lazy('Ibaraki'),), 12 ('tochigi', ugettext_lazy('Tochigi'),), 13 ('gunma', ugettext_lazy('Gunma'),), 14 ('saitama', ugettext_lazy('Saitama'),), 15 ('chiba', ugettext_lazy('Chiba'),), 16 ('tokyo', ugettext_lazy('Tokyo'),), 17 ('kanagawa', ugettext_lazy('Kanagawa'),), 18 ('yamanashi', ugettext_lazy('Yamanashi'),), 19 ('nagano', ugettext_lazy('Nagano'),), 20 ('niigata', ugettext_lazy('Niigata'),), 21 ('toyama', ugettext_lazy('Toyama'),), 22 ('ishikawa', ugettext_lazy('Ishikawa'),), 23 ('fukui', ugettext_lazy('Fukui'),), 24 ('gifu', ugettext_lazy('Gifu'),), 25 ('shizuoka', ugettext_lazy('Shizuoka'),), 26 ('aichi', ugettext_lazy('Aichi'),), 27 ('mie', ugettext_lazy('Mie'),), 28 ('shiga', ugettext_lazy('Shiga'),), 29 ('kyoto', ugettext_lazy('Kyoto'),), 30 ('osaka', ugettext_lazy('Osaka'),), 31 ('hyogo', ugettext_lazy('Hyogo'),), 32 ('nara', ugettext_lazy('Nara'),), 33 ('wakayama', ugettext_lazy('Wakayama'),), 34 ('tottori', ugettext_lazy('Tottori'),), 35 ('shimane', ugettext_lazy('Shimane'),), 36 ('okayama', ugettext_lazy('Okayama'),), 37 ('hiroshima', ugettext_lazy('Hiroshima'),), 38 ('yamaguchi', ugettext_lazy('Yamaguchi'),), 39 ('tokushima', ugettext_lazy('Tokushima'),), 40 ('kagawa', ugettext_lazy('Kagawa'),), 41 ('ehime', ugettext_lazy('Ehime'),), 42 ('kochi', ugettext_lazy('Kochi'),), 43 ('fukuoka', ugettext_lazy('Fukuoka'),), 44 ('saga', ugettext_lazy('Saga'),), 45 ('nagasaki', ugettext_lazy('Nagasaki'),), 46 ('kumamoto', ugettext_lazy('Kumamoto'),), 47 ('oita', ugettext_lazy('Oita'),), 48 ('miyazaki', ugettext_lazy('Miyazaki'),), 49 ('kagoshima', ugettext_lazy('Kagoshima'),), 50 ('okinawa', ugettext_lazy('Okinawa'),), 51 51 ) django/trunk/django/contrib/localflavor/no/forms.py
r4888 r5609 7 7 from django.newforms import ValidationError 8 8 from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES 9 from django.utils.translation import gettext9 from django.utils.translation import ugettext 10 10 11 11 class NOZipCodeField(RegexField): … … 13 13 super(NOZipCodeField, self).__init__(r'^\d{4}$', 14 14 max_length=None, min_length=None, 15 error_message= gettext(u'Enter a zip code in the format XXXX.'),16 *args, **kwargs)15 error_message=ugettext('Enter a zip code in the format XXXX.'), 16 *args, **kwargs) 17 17 18 18 class NOMunicipalitySelect(Select): … … 34 34 return u'' 35 35 36 msg = gettext(u'Enter a valid Norwegian social security number.')36 msg = ugettext(u'Enter a valid Norwegian social security number.') 37 37 if not re.match(r'^\d{11}$', value): 38 38 raise ValidationError(msg) … … 61 61 else: 62 62 self.gender = 'M' 63 63 64 64 digits = map(int, list(value)) 65 65 weight_1 = [3, 7, 6, 1, 8, 9, 4, 5, 2, 1, 0] … … 75 75 76 76 return value 77 77 django/trunk/django/contrib/localflavor/no/no_municipalities.py
r4875 r5609 1 # -*- coding: iso-8859-1-*-1 # -*- coding: utf-8 -*- 2 2 """ 3 3 An alphabetical list of Norwegian municipalities (fylker) fro use as `choices` … … 16 16 ('hordaland', u'Hordaland'), 17 17 ('janmayen', u'Jan Mayen'), 18 ('moreogromsdal', u'M �g Romsdal'),19 ('nordtrondelag', u'Nord-Tr �ag'),18 ('moreogromsdal', u'Møre og Romsdal'), 19 ('nordtrondelag', u'Nord-Trøndelag'), 20 20 ('nordland', u'Nordland'), 21 21 ('oppland', u'Oppland'), … … 24 24 ('sognogfjordane', u'Sogn og Fjordane'), 25 25 ('svalbard', u'Svalbard'), 26 ('sortrondelag', u'S ��ag'),26 ('sortrondelag', u'Sør-Trøndelag'), 27 27 ('telemark', u'Telemark'), 28 28 ('troms', u'Troms'), 29 29 ('vestagder', u'Vest-Agder'), 30 30 ('vestfold', u'Vestfold'), 31 ('ostfold', u' �tfold')31 ('ostfold', u'Østfold') 32 32 ) django/trunk/django/contrib/localflavor/uk/forms.py
r4527 r5609 4 4 5 5 from django.newforms.fields import RegexField 6 from django.utils.translation import gettext6 from django.utils.translation import ugettext 7 7 8 8 class UKPostcodeField(RegexField): … … 16 16 super(UKPostcodeField, self).__init__(r'^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW]) [0-9][ABD-HJLNP-UW-Z]{2})$', 17 17 max_length=None, min_length=None, 18 error_message= gettext(u'Enter a postcode. A space is required between the two postcode parts.'),18 error_message=ugettext(u'Enter a postcode. A space is required between the two postcode parts.'), 19 19 *args, **kwargs) django/trunk/django/contrib/localflavor/us/forms.py
r4918 r5609 6 6 from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES 7 7 from django.utils.encoding import smart_unicode 8 from django.utils.translation import gettext8 from django.utils.translation import ugettext 9 9 import re 10 10 … … 16 16 super(USZipCodeField, self).__init__(r'^\d{5}(?:-\d{4})?$', 17 17 max_length=None, min_length=None, 18 error_message= gettext(u'Enter a zip code in the format XXXXX or XXXXX-XXXX.'),19 *args, **kwargs)18 error_message=ugettext('Enter a zip code in the format XXXXX or XXXXX-XXXX.'), 19 *args, **kwargs) 20 20 21 21 class USPhoneNumberField(Field): … … 39 39 * No group consists entirely of zeroes. 40 40 * The leading group is not "666" (block "666" will never be allocated). 41 * The number is not in the promotional block 987-65-4320 through 987-65-4329,42 which are permanently invalid.41 * The number is not in the promotional block 987-65-4320 through 42 987-65-4329, which are permanently invalid. 43 43 * The number is not one known to be invalid due to otherwise widespread 44 promotional use or distribution (e.g., the Woolworth's number or the 196245 promotional number).44 promotional use or distribution (e.g., the Woolworth's number or the 45 1962 promotional number). 46 46 """ 47 47 def clean(self, value): … … 49 49 if value in EMPTY_VALUES: 50 50 return u'' 51 msg = gettext(u'Enter a valid U.S. Social Security number in XXX-XX-XXXX format.')51 msg = ugettext('Enter a valid U.S. Social Security number in XXX-XX-XXXX format.') 52 52 match = re.match(ssn_re, value) 53 53 if not match: … … 76 76 """ 77 77 def clean(self, value): 78 from us_states import STATES_NORMALIZED # relative import78 from us_states import STATES_NORMALIZED 79 79 super(USStateField, self).clean(value) 80 80 if value in EMPTY_VALUES: … … 96 96 """ 97 97 def __init__(self, attrs=None): 98 from us_states import STATE_CHOICES # relative import98 from us_states import STATE_CHOICES 99 99 super(USStateSelect, self).__init__(attrs, choices=STATE_CHOICES) django/trunk/django/contrib/markup/templatetags/markup.py
r4265 r5609 17 17 from django import template 18 18 from django.conf import settings 19 from django.utils.encoding import smart_str, force_unicode 19 20 20 21 register = template.Library() … … 26 27 if settings.DEBUG: 27 28 raise template.TemplateSyntaxError, "Error in {% textile %} filter: The Python textile library isn't installed." 28 return value29 return force_unicode(value) 29 30 else: 30 return textile.textile(value, encoding=settings.DEFAULT_CHARSET, output=settings.DEFAULT_CHARSET)31 return force_unicode(textile.textile(smart_str(value), encoding='utf-8', output='utf-8')) 31 32 32 33 def markdown(value): … … 36 37 if settings.DEBUG: 37 38 raise template.TemplateSyntaxError, "Error in {% markdown %} filter: The Python markdown library isn't installed." 38 return value39 return force_unicode(value) 39 40 else: 40 return markdown.markdown(value)41 return force_unicode(markdown.markdown(smart_str(value))) 41 42 42 43 def restructuredtext(value): … … 46 47 if settings.DEBUG: 47 48 raise template.TemplateSyntaxError, "Error in {% restructuredtext %} filter: The Python docutils library isn't installed." 48 return value49 return force_unicode(value) 49 50 else: 50 51 docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {}) 51 parts = publish_parts(source= value, writer_name="html4css1", settings_overrides=docutils_settings)52 return parts["fragment"]52 parts = publish_parts(source=smart_str(value), writer_name="html4css1", settings_overrides=docutils_settings) 53 return force_unicode(parts["fragment"]) 53 54 54 55 register.filter(textile) django/trunk/django/contrib/redirects/models.py
r4265 r5609 1 1 from django.db import models 2 2 from django.contrib.sites.models import Site 3 from django.utils.translation import gettext_lazy as _3 from django.utils.translation import ugettext_lazy as _ 4 4 5 5 class Redirect(models.Model): … … 21 21 search_fields = ('old_path', 'new_path') 22 22 23 def __ str__(self):24 return "%s ---> %s" % (self.old_path, self.new_path)23 def __unicode__(self): 24 return u"%s ---> %s" % (self.old_path, self.new_path) django/trunk/django/contrib/sessions/models.py
r5470 r5609 2 2 import cPickle as pickle 3 3 from django.db import models 4 from django.utils.translation import gettext_lazy as _4 from django.utils.translation import ugettext_lazy as _ 5 5 from django.conf import settings 6 6 django/trunk/django/contrib/sitemaps/views.py
r5091 r5609 3 3 from django.contrib.sites.models import Site 4 4 from django.core import urlresolvers 5 from django.utils.encoding import smart_str 5 6 6 7 def index(request, sitemaps): … … 27 28 else: 28 29 urls.extend(site.get_urls()) 29 xml = loader.render_to_string('sitemap.xml', {'urlset': urls})30 xml = smart_str(loader.render_to_string('sitemap.xml', {'urlset': urls})) 30 31 return HttpResponse(xml, mimetype='application/xml') django/trunk/django/contrib/sites/models.py
r4265 r5609 1 1 from django.db import models 2 from django.utils.translation import gettext_lazy as _2 from django.utils.translation import ugettext_lazy as _ 3 3 4 4 class SiteManager(models.Manager): … … 20 20 search_fields = ('domain', 'name') 21 21 22 def __ str__(self):22 def __unicode__(self): 23 23 return self.domain django/trunk/django/contrib/syndication/feeds.py
r5045 r5609 3 3 from django.contrib.sites.models import Site 4 4 from django.utils import feedgenerator 5 from django.utils.encoding import smart_unicode 5 6 from django.conf import settings 6 7 7 8 def add_domain(domain, url): 8 9 if not url.startswith('http://'): 10 # 'url' must already be ASCII and URL-quoted, so no need for encoding 11 # conversions here. 9 12 url = u'http://%s%s' % (domain, url) 10 13 return url … … 98 101 if enc_url: 99 102 enc = feedgenerator.Enclosure( 100 url = enc_url.decode('utf-8'),101 length = s tr(self.__get_dynamic_attr('item_enclosure_length', item)).decode('utf-8'),102 mime_type = s elf.__get_dynamic_attr('item_enclosure_mime_type', item).decode('utf-8'),103 url = smart_unicode(enc_url), 104 length = smart_unicode(self.__get_dynamic_attr('item_enclosure_length', item)), 105 mime_type = smart_unicode(self.__get_dynamic_attr('item_enclosure_mime_type', item)) 103 106 ) 104 107 author_name = self.__get_dynamic_attr('item_author_name', item) … … 109 112 author_email = author_link = None 110 113 feed.add_item( 111 title = title_tmp.render(Context({'obj': item, 'site': current_site})) .decode('utf-8'),114 title = title_tmp.render(Context({'obj': item, 'site': current_site})), 112 115 link = link, 113 description = description_tmp.render(Context({'obj': item, 'site': current_site})) .decode('utf-8'),116 description = description_tmp.render(Context({'obj': item, 'site': current_site})), 114 117 unique_id = link, 115 118 enclosure = enc, django/trunk/django/contrib/webdesign/lorem_ipsum.py
r5190 r5609 6 6 7 7 COMMON_P = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' 8 WORDS = ('exercitationem', 'perferendis', 'perspiciatis', 'laborum', 'eveniet', 'sunt', 'iure', 'nam', 'nobis', 'eum', 'cum', 'officiis', 'excepturi', 'odio', 'consectetur', 'quasi', 'aut', 'quisquam', 'vel', 'eligendi', 'itaque', 'non', 'odit', 'tempore', 'quaerat', 'dignissimos', 'facilis', 'neque', 'nihil', 'expedita', 'vitae', 'vero', 'ipsum', 'nisi', 'animi', 'cumque', 'pariatur', 'velit', 'modi', 'natus', 'iusto', 'eaque', 'sequi', 'illo', 'sed', 'ex', 'et', 'voluptatibus', 'tempora', 'veritatis', 'ratione', 'assumenda', 'incidunt', 'nostrum', 'placeat', 'aliquid', 'fuga', 'provident', 'praesentium', 'rem', 'necessitatibus', 'suscipit', 'adipisci', 'quidem', 'possimus', 'voluptas', 'debitis', 'sint', 'accusantium', 'unde', 'sapiente', 'voluptate', 'qui', 'aspernatur', 'laudantium', 'soluta', 'amet', 'quo', 'aliquam', 'saepe', 'culpa', 'libero', 'ipsa', 'dicta', 'reiciendis', 'nesciunt', 'doloribus', 'autem', 'impedit', 'minima', 'maiores', 'repudiandae', 'ipsam', 'obcaecati', 'ullam', 'enim', 'totam', 'delectus', 'ducimus', 'quis', 'voluptates', 'dolores', 'molestiae', 'harum', 'dolorem', 'quia', 'voluptatem', 'molestias', 'magni', 'distinctio', 'omnis', 'illum', 'dolorum', 'voluptatum', 'ea', 'quas', 'quam', 'corporis', 'quae', 'blanditiis', 'atque', 'deserunt', 'laboriosam', 'earum', 'consequuntur', 'hic', 'cupiditate', 'quibusdam', 'accusamus', 'ut', 'rerum', 'error', 'minus', 'eius', 'ab', 'ad', 'nemo', 'fugit', 'officia', 'at', 'in', 'id', 'quos', 'reprehenderit', 'numquam', 'iste', 'fugiat', 'sit', 'inventore', 'beatae', 'repellendus', 'magnam', 'recusandae', 'quod', 'explicabo', 'doloremque', 'aperiam', 'consequatur', 'asperiores', 'commodi', 'optio', 'dolor', 'labore', 'temporibus', 'repellat', 'veniam', 'architecto', 'est', 'esse', 'mollitia', 'nulla', 'a', 'similique', 'eos', 'alias', 'dolore', 'tenetur', 'deleniti', 'porro', 'facere', 'maxime', 'corrupti') 9 COMMON_WORDS = ('lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua') 8 9 WORDS = ('exercitationem', 'perferendis', 'perspiciatis', 'laborum', 'eveniet', 10 'sunt', 'iure', 'nam', 'nobis', 'eum', 'cum', 'officiis', 'excepturi', 11 'odio', 'consectetur', 'quasi', 'aut', 'quisquam', 'vel', 'eligendi', 12 'itaque', 'non', 'odit', 'tempore', 'quaerat', 'dignissimos', 13 'facilis', 'neque', 'nihil', 'expedita', 'vitae', 'vero', 'ipsum', 14 'nisi', 'animi', 'cumque', 'pariatur', 'velit', 'modi', 'natus', 15 'iusto', 'eaque', 'sequi', 'illo', 'sed', 'ex', 'et', 'voluptatibus', 16 'tempora', 'veritatis', 'ratione', 'assumenda', 'incidunt', 'nostrum', 17 'placeat', 'aliquid', 'fuga', 'provident', 'praesentium', 'rem', 18 'necessitatibus', 'suscipit', 'adipisci', 'quidem', 'possimus', 19 'voluptas', 'debitis', 'sint', 'accusantium', 'unde', 'sapiente', 20 'voluptate', 'qui', 'aspernatur', 'laudantium', 'soluta', 'amet', 21 'quo', 'aliquam', 'saepe', 'culpa', 'libero', 'ipsa', 'dicta', 22 'reiciendis', 'nesciunt', 'doloribus', 'autem', 'impedit', 'minima', 23 'maiores', 'repudiandae', 'ipsam', 'obcaecati', 'ullam', 'enim', 24 'totam', 'delectus', 'ducimus', 'quis', 'voluptates', 'dolores', 25 'molestiae', 'harum', 'dolorem', 'quia', 'voluptatem', 'molestias', 26 'magni', 'distinctio', 'omnis', 'illum', 'dolorum', 'voluptatum', 'ea', 27 'quas', 'quam', 'corporis', 'quae', 'blanditiis', 'atque', 'deserunt', 28 'laboriosam', 'earum', 'consequuntur', 'hic', 'cupiditate', 29 'quibusdam', 'accusamus', 'ut', 'rerum', 'error', 'minus', 'eius', 30 'ab', 'ad', 'nemo', 'fugit', 'officia', 'at', 'in', 'id', 'quos', 31 'reprehenderit', 'numquam', 'iste', 'fugiat', 'sit', 'inventore', 32 'beatae', 'repellendus', 'magnam', 'recusandae', 'quod', 'explicabo', 33 'doloremque', 'aperiam', 'consequatur', 'asperiores', 'commodi', 34 'optio', 'dolor', 'labore', 'temporibus', 'repellat', 'veniam', 35 'architecto', 'est', 'esse', 'mollitia', 'nulla', 'a', 'similique', 36 'eos', 'alias', 'dolore', 'tenetur', 'deleniti', 'porro', 'facere', 37 'maxime', 'corrupti') 38 39 COMMON_WORDS = ('lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 40 'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 41 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua') 10 42 11 43 def sentence(): … … 18 50 # Determine the number of comma-separated sections and number of words in 19 51 # each section for this sentence. 20 sections = [ ' '.join(random.sample(WORDS, random.randint(3, 12))) for i in range(random.randint(1, 5))]21 s = ', '.join(sections)52 sections = [u' '.join(random.sample(WORDS, random.randint(3, 12))) for i in range(random.randint(1, 5))] 53 s = u', '.join(sections) 22 54 # Convert to sentence case and add end punctuation. 23 return '%s%s%s' % (s[0].upper(), s[1:], random.choice('?.'))55 return u'%s%s%s' % (s[0].upper(), s[1:], random.choice('?.')) 24 56 25 57 def paragraph(): … … 29 61 The paragraph consists of between 1 and 4 sentences, inclusive. 30 62 """ 31 return ' '.join([sentence() for i in range(random.randint(1, 4))])63 return u' '.join([sentence() for i in range(random.randint(1, 4))]) 32 64 33 65 def paragraphs(count, common=True): … … 67 99 else: 68 100 word_list = word_list[:count] 69 return ' '.join(word_list)101 return u' '.join(word_list) django/trunk/django/contrib/webdesign/templatetags/webdesign.py
r5189 r5609 19 19 if self.method == 'p': 20 20 paras = ['<p>%s</p>' % p for p in paras] 21 return '\n\n'.join(paras)21 return u'\n\n'.join(paras) 22 22 23 23 #@register.tag django/trunk/django/contrib/webdesign/tests.py
r5296 r5609 3 3 r""" 4 4 >>> words(7) 5 'lorem ipsum dolor sit amet consectetur adipisicing'5 u'lorem ipsum dolor sit amet consectetur adipisicing' 6 6 7 7 >>> paragraphs(1) django/trunk/django/core/handlers/modpython.py
r5091 r5609 50 50 self._post, self._files = http.parse_file_upload(self._req.headers_in, self.raw_post_data) 51 51 else: 52 self._post, self._files = http.QueryDict(self.raw_post_data ), datastructures.MultiValueDict()52 self._post, self._files = http.QueryDict(self.raw_post_data, encoding=self._encoding), datastructures.MultiValueDict() 53 53 54 54 def _get_request(self): … … 59 59 def _get_get(self): 60 60 if not hasattr(self, '_get'): 61 self._get = http.QueryDict(self._req.args )61 self._get = http.QueryDict(self._req.args, encoding=self._encoding) 62 62 return self._get 63 63 … … 161 161 for key, value in response.headers.items(): 162 162 if key != 'Content-Type': 163 req.headers_out[ key] = value163 req.headers_out[str(key)] = str(value) 164 164 for c in response.cookies.values(): 165 165 req.headers_out.add('Set-Cookie', c.output(header='')) django/trunk/django/core/handlers/wsgi.py
r5091 r5609 114 114 self._post, self._files = http.parse_file_upload(header_dict, self.raw_post_data) 115 115 else: 116 self._post, self._files = http.QueryDict(self.raw_post_data ), datastructures.MultiValueDict()116 self._post, self._files = http.QueryDict(self.raw_post_data, encoding=self._encoding), datastructures.MultiValueDict() 117 117 else: 118 self._post, self._files = http.QueryDict('' ), datastructures.MultiValueDict()118 self._post, self._files = http.QueryDict('', encoding=self._encoding), datastructures.MultiValueDict() 119 119 120 120 def _get_request(self): … … 126 126 if not hasattr(self, '_get'): 127 127 # The WSGI spec says 'QUERY_STRING' may be absent. 128 self._get = http.QueryDict(self.environ.get('QUERY_STRING', '') )128 self._get = http.QueryDict(self.environ.get('QUERY_STRING', ''), encoding=self._encoding) 129 129 return self._get 130 130 … … 201 201 status_text = 'UNKNOWN STATUS CODE' 202 202 status = '%s %s' % (response.status_code, status_text) 203 response_headers = response.headers.items()203 response_headers = [(str(k), str(v)) for k, v in response.headers.items()] 204 204 for c in response.cookies.values(): 205 response_headers.append(('Set-Cookie', c.output(header='')))205 response_headers.append(('Set-Cookie', str(c.output(header='')))) 206 206 start_response(status, response_headers) 207 207 return response django/trunk/django/core/mail.py
r5582 r5609 4 4 5 5 from django.conf import settings 6 from django.utils.encoding import smart_str, force_unicode 6 7 from email import Charset, Encoders 7 8 from email.MIMEText import MIMEText … … 9 10 from email.MIMEBase import MIMEBase 10 11 from email.Header import Header 11 from email.Utils import formatdate 12 from email.Utils import formatdate, parseaddr, formataddr 12 13 import mimetypes 13 14 import os … … 68 69 if '\n' in val or '\r' in val: 69 70 raise BadHeaderError, "Header values can't contain newlines (got %r for header %r)" % (val, name) 70 if name == "Subject": 71 val = Header(val, settings.DEFAULT_CHARSET) 71 try: 72 val = str(force_unicode(val)) 73 except UnicodeEncodeError: 74 if name.lower() in ('to', 'from', 'cc'): 75 result = [] 76 for item in val.split(', '): 77 nm, addr = parseaddr(item) 78 nm = str(Header(nm, settings.DEFAULT_CHARSET)) 79 result.append(formataddr((nm, str(addr)))) 80 val = ', '.join(result) 81 else: 82 val = Header(force_unicode(val), settings.DEFAULT_CHARSET) 72 83 MIMEText.__setitem__(self, name, val) 73 84 … … 77 88 if '\n' in val or '\r' in val: 78 89 raise BadHeaderError, "Header values can't contain newlines (got %r for header %r)" % (val, name) 79 if name == "Subject": 80 val = Header(val, settings.DEFAULT_CHARSET) 90 try: 91 val = str(force_unicode(val)) 92 except UnicodeEncodeError: 93 if name.lower() in ('to', 'from', 'cc'): 94 result = [] 95 for item in val.split(', '): 96 nm, addr = parseaddr(item) 97 nm = str(Header(nm, settings.DEFAULT_CHARSET)) 98 result.append(formataddr((nm, str(addr)))) 99 val = ', '.join(result) 100 else: 101 val = Header(force_unicode(val), settings.DEFAULT_CHARSET) 81 102 MIMEMultipart.__setitem__(self, name, val) 82 103 … … 177 198 def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, 178 199 connection=None, attachments=None, headers=None): 200 """ 201 Initialise a single email message (which can be sent to multiple 202 recipients). 203 204 All strings used to create the message can be unicode strings (or UTF-8 205 bytestrings). The SafeMIMEText class will handle any necessary encoding 206 conversions. 207 """ 179 208 self.to = to or [] 180 209 self.bcc = bcc or [] … … 193 222 def message(self): 194 223 encoding = self.encoding or settings.DEFAULT_CHARSET 195 msg = SafeMIMEText(s elf.body, self.content_subtype, encoding)224 msg = SafeMIMEText(smart_str(self.body, settings.DEFAULT_CHARSET), self.content_subtype, encoding) 196 225 if self.attachments: 197 226 body_msg = msg django/trunk/django/core/management.py
r5593 r5609 428 428 if os.path.exists(sql_file): 429 429 fp = open(sql_file, 'U') 430 for statement in statements.split(fp.read() ):430 for statement in statements.split(fp.read().decode(settings.FILE_CHARSET)): 431 431 # Remove any comments from the file 432 statement = re.sub( r"--.*[\n\Z]", "", statement)432 statement = re.sub(ur"--.*[\n\Z]", "", statement) 433 433 if statement.strip(): 434 output.append(statement + ";")434 output.append(statement + u";") 435 435 fp.close() 436 436 django/trunk/django/core/serializers/base.py
r5075 r5609 8 8 from StringIO import StringIO 9 9 from django.db import models 10 from django.utils.encoding import smart_str, smart_unicode 10 11 11 12 class SerializationError(Exception): … … 60 61 else: 61 62 value = field.flatten_data(follow=None, obj=obj).get(field.name, "") 62 return s tr(value)63 return smart_unicode(value) 63 64 64 65 def start_serialization(self): … … 155 156 156 157 def __repr__(self): 157 return "<DeserializedObject: %s>" % s tr(self.object)158 return "<DeserializedObject: %s>" % smart_str(self.object) 158 159 159 160 def save(self, save_m2m=True): django/trunk/django/core/serializers/__init__.py
r4712 r5609 7 7 >>> json = serializers.serialize("json", some_query_set) 8 8 >>> objects = list(serializers.deserialize("json", json)) 9 9 10 10 To add your own serializers, use the SERIALIZATION_MODULES setting:: 11 11 … … 31 31 BUILTIN_SERIALIZERS["yaml"] = "django.core.serializers.pyyaml" 32 32 except ImportError: 33 pass 33 pass 34 34 35 35 _serializers = {} 36 36 37 37 def register_serializer(format, serializer_module): 38 38 """Register a new serializer by passing in a module name.""" 39 39 module = __import__(serializer_module, {}, {}, ['']) 40 40 _serializers[format] = module 41 41 42 42 def unregister_serializer(format): 43 43 """Unregister a given serializer""" 44 44 del _serializers[format] 45 45 46 46 def get_serializer(format): 47 47 if not _serializers: … … 53 53 _load_serializers() 54 54 return _serializers.keys() 55 55 56 56 def get_deserializer(format): 57 57 if not _serializers: 58 58 _load_serializers() 59 59 return _serializers[format].Deserializer 60 60 61 61 def serialize(format, queryset, **options): 62 62 """ django/trunk/django/core/serializers/python.py
r5371 r5609 8 8 from django.core.serializers import base 9 9 from django.db import models 10 from django.utils.encoding import smart_unicode 10 11 11 12 class Serializer(base.Serializer): … … 13 14 Serializes a QuerySet to basic Python objects. 14 15 """ 15 16 16 17 def start_serialization(self): 17 18 self._current = None 18 19 self.objects = [] 19 20 20 21 def end_serialization(self): 21 22 pass 22 23 23 24 def start_object(self, obj): 24 25 self._current = {} 25 26 26 27 def end_object(self, obj): 27 28 self.objects.append({ 28 "model" : s tr(obj._meta),29 "pk" : s tr(obj._get_pk_val()),29 "model" : smart_unicode(obj._meta), 30 "pk" : smart_unicode(obj._get_pk_val()), 30 31 "fields" : self._current 31 32 }) 32 33 self._current = None 33 34 34 35 def handle_field(self, obj, field): 35 36 self._current[field.name] = getattr(obj, field.name) 36 37 37 38 def handle_fk_field(self, obj, field): 38 39 related = getattr(obj, field.name) … … 45 46 related = getattr(related, field.rel.field_name) 46 47 self._current[field.name] = related 47 48 48 49 def handle_m2m_field(self, obj, field): 49 50 self._current[field.name] = [related._get_pk_val() for related in getattr(obj, field.name).iterator()] 50 51 51 52 def getvalue(self): 52 53 return self.objects … … 55 56 """ 56 57 Deserialize simple Python objects back into Django ORM instances. 57 58 58 59 It's expected that you pass the Python objects themselves (instead of a 59 60 stream or a string) to the constructor … … 65 66 data = {Model._meta.pk.attname : Model._meta.pk.to_python(d["pk"])} 66 67 m2m_data = {} 67 68 68 69 # Handle each field 69 70 for (field_name, field_value) in d["fields"].iteritems(): 70 if isinstance(field_value, unicode):71 field_value = field_value.encode(options.get("encoding", settings.DEFAULT_CHARSET))72 71 if isinstance(field_value, str): 72 field_value = smart_unicode(field_value, options.get("encoding", settings.DEFAULT_CHARSET), strings_only=True) 73 73 74 field = Model._meta.get_field(field_name) 74 75 75 76 # Handle M2M relations 76 77 if field.rel and isinstance(field.rel, models.ManyToManyRel): 77 pks = []78 78 m2m_convert = field.rel.to._meta.pk.to_python 79 for pk in field_value: 80 if isinstance(pk, unicode): 81 pks.append(m2m_convert(pk.encode(options.get("encoding", settings.DEFAULT_CHARSET)))) 82 else: 83 pks.append(m2m_convert(pk)) 84 m2m_data[field.name] = pks 85 79 m2m_data[field.name] = [m2m_convert(smart_unicode(pk)) for pk in field_value] 80 86 81 # Handle FK fields 87 82 elif field.rel and isinstance(field.rel, models.ManyToOneRel): … … 90 85 else: 91 86 data[field.attname] = None 92 87 93 88 # Handle all other fields 94 89 else: 95 90 data[field.name] = field.to_python(field_value) 96 91 97 92 yield base.DeserializedObject(Model(**data), m2m_data) 98 93 … … 106 101 Model = None 107 102 if Model is None: 108 raise base.DeserializationError( "Invalid model identifier: '%s'" % model_identifier)103 raise base.DeserializationError(u"Invalid model identifier: '%s'" % model_identifier) 109 104 return Model django/trunk/django/core/serializers/pyyaml.py
r5409 r5609 22 22 self.options.pop('fields', None) 23 23 yaml.dump(self.objects, self.stream, **self.options) 24 24 25 25 def getvalue(self): 26 26 return self.stream.getvalue() … … 36 36 for obj in PythonDeserializer(yaml.load(stream)): 37 37 yield obj 38 38 django/trunk/django/core/serializers/xml_serializer.py
r5371 r5609 7 7 from django.db import models 8 8 from django.utils.xmlutils import SimplerXMLGenerator 9 from django.utils.encoding import smart_unicode 9 10 from xml.dom import pulldom 10 11 … … 13 14 Serializes a QuerySet to XML. 14 15 """ 15 16 16 17 def indent(self, level): 17 18 if self.options.get('indent', None) is not None: … … 25 26 self.xml.startDocument() 26 27 self.xml.startElement("django-objects", {"version" : "1.0"}) 27 28 28 29 def end_serialization(self): 29 30 """ … … 33 34 self.xml.endElement("django-objects") 34 35 self.xml.endDocument() 35 36 36 37 def start_object(self, obj): 37 38 """ … … 40 41 if not hasattr(obj, "_meta"): 41 42 raise base.SerializationError("Non-model object (%s) encountered during serialization" % type(obj)) 42 43 43 44 self.indent(1) 44 45 self.xml.startElement("object", { 45 "pk" : s tr(obj._get_pk_val()),46 "model" : s tr(obj._meta),46 "pk" : smart_unicode(obj._get_pk_val()), 47 "model" : smart_unicode(obj._meta), 47 48 }) 48 49 49 50 def end_object(self, obj): 50 51 """ … … 53 54 self.indent(1) 54 55 self.xml.endElement("object") 55 56 56 57 def handle_field(self, obj, field): 57 58 """ … … 64 65 "type" : field.get_internal_type() 65 66 }) 66 67 67 68 # Get a "string version" of the object's data (this is handled by the 68 # serializer base class). 69 # serializer base class). 69 70 if getattr(obj, field.name) is not None: 70 71 value = self.get_string_value(obj, field) 71 self.xml.characters(s tr(value))72 self.xml.characters(smart_unicode(value)) 72 73 else: 73 74 self.xml.addQuickElement("None") 74 75 75 76 self.xml.endElement("field") 76 77 77 78 def handle_fk_field(self, obj, field): 78 79 """ … … 89 90 # Related to remote object via other field 90 91 related = getattr(related, field.rel.field_name) 91 self.xml.characters(s tr(related))92 self.xml.characters(smart_unicode(related)) 92 93 else: 93 94 self.xml.addQuickElement("None") 94 95 self.xml.endElement("field") 95 96 96 97 def handle_m2m_field(self, obj, field): 97 98 """ … … 102 103 self._start_relational_field(field) 103 104 for relobj in getattr(obj, field.name).iterator(): 104 self.xml.addQuickElement("object", attrs={"pk" : s tr(relobj._get_pk_val())})105 self.xml.addQuickElement("object", attrs={"pk" : smart_unicode(relobj._get_pk_val())}) 105 106 self.xml.endElement("field") 106 107 107 108 def _start_relational_field(self, field): 108 109 """ … … 113 114 "name" : field.name, 114 115 "rel" : field.rel.__class__.__name__, 115 "to" : s tr(field.rel.to._meta),116 "to" : smart_unicode(field.rel.to._meta), 116 117 }) 117 118 118 119 class Deserializer(base.Deserializer): 119 120 """ 120 121 Deserialize XML. 121 122 """ 122 123 123 124 def __init__(self, stream_or_string, **options): 124 125 super(Deserializer, self).__init__(stream_or_string, **options) 125 self.encoding = self.options.get("encoding", settings.DEFAULT_CHARSET) 126 self.event_stream = pulldom.parse(self.stream) 127 126 self.event_stream = pulldom.parse(self.stream) 127 128 128 def next(self): 129 129 for event, node in self.event_stream: … … 132 132 return self._handle_object(node) 133 133 raise StopIteration 134 134 135 135 def _handle_object(self, node): 136 136 """ 137 137 Convert an <object> node to a DeserializedObject. 138 138 """ 139 # Look up the model using the model loading mechanism. If this fails, bail. 139 # Look up the model using the model loading mechanism. If this fails, 140 # bail. 140 141 Model = self._get_model_from_node(node, "model") 141 142 142 143 # Start building a data dictionary from the object. If the node is 143 144 # missing the pk attribute, bail. … … 147 148 148 149 data = {Model._meta.pk.attname : Model._meta.pk.to_python(pk)} 149 150 150 151 # Also start building a dict of m2m data (this is saved as 151 152 # {m2m_accessor_attribute : [list_of_related_objects]}) 152 153 m2m_data = {} 153 154 154 155 # Deseralize each field. 155 156 for field_node in node.getElementsByTagName("field"): … … 159 160 if not field_name: 160 161 raise base.DeserializationError("<field> node is missing the 'name' attribute") 161 162 162 163 # Get the field from the Model. This will raise a 163 164 # FieldDoesNotExist if, well, the field doesn't exist, which will 164 165 # be propagated correctly. 165 166 field = Model._meta.get_field(field_name) 166 167 167 168 # As is usually the case, relation fields get the special treatment. 168 169 if field.rel and isinstance(field.rel, models.ManyToManyRel): … … 174 175 value = None 175 176 else: 176 value = field.to_python(getInnerText(field_node).strip() .encode(self.encoding))177 value = field.to_python(getInnerText(field_node).strip()) 177 178 data[field.name] = value 178 179 179 180 # Return a DeserializedObject so that the m2m data has a place to live. 180 181 return base.DeserializedObject(Model(**data), m2m_data) 181 182 182 183 def _handle_fk_field_node(self, node, field): 183 184 """ … … 189 190 else: 190 191 return field.rel.to._meta.get_field(field.rel.field_name).to_python( 191 getInnerText(node).strip() .encode(self.encoding))192 192 getInnerText(node).strip()) 193 193 194 def _handle_m2m_field_node(self, node, field): 194 195 """ 195 Handle a <field> node for a ManyToManyField 196 Handle a <field> node for a ManyToManyField. 196 197 """ 197 198 return [field.rel.to._meta.pk.to_python( 198 c.getAttribute("pk") .encode(self.encoding))199 c.getAttribute("pk")) 199 200 for c in node.getElementsByTagName("object")] 200 201 201 202 def _get_model_from_node(self, node, attr): 202 203 """ … … 218 219 (node.nodeName, model_identifier)) 219 220 return Model 220 221 221 222 222 223 def getInnerText(node): 223 224 """ … … 233 234 else: 234 235 pass 235 return "".join(inner_text) 236 return u"".join(inner_text) 237 django/trunk/django/core/urlresolvers.py
r5538 r5609 10 10 from django.http import Http404 11 11 from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist 12 from django.utils.encoding import iri_to_uri 12 13 from django.utils.functional import memoize 13 14 import re … … 38 39 during the import fail and the string is returned. 39 40 """ 40 if not callable(lookup_view): 41 mod_name, func_name = get_mod_func(lookup_view) 42 try: 43 if func_name != '': 44 lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name) 45 except (ImportError, AttributeError): 46 if not can_fail: 47 raise 41 try: 42 # Bail out early if lookup_view is not ASCII. This can't be a function. 43 lookup_view = lookup_view.encode('ascii') 44 45 if not callable(lookup_view): 46 mod_name, func_name = get_mod_func(lookup_view) 47 try: 48 if func_name != '': 49 lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name) 50 except (ImportError, AttributeError): 51 if not can_fail: 52 raise 53 except UnicodeEncodeError: 54 pass 48 55 return lookup_view 49 56 get_callable = memoize(get_callable, _callable_cache) … … 266 273 raise NoReverseMatch 267 274 if lookup_view in self.reverse_dict: 268 return ''.join([reverse_helper(part.regex, *args, **kwargs) for part in self.reverse_dict[lookup_view]])275 return u''.join([reverse_helper(part.regex, *args, **kwargs) for part in self.reverse_dict[lookup_view]]) 269 276 raise NoReverseMatch 270 277 … … 280 287 args = args or [] 281 288 kwargs = kwargs or {} 282 return '/' + get_resolver(urlconf).reverse(viewname, *args, **kwargs)283 289 return iri_to_uri(u'/' + get_resolver(urlconf).reverse(viewname, *args, **kwargs)) 290 django/trunk/django/core/validators.py
r5302 r5609 11 11 import urllib2 12 12 from django.conf import settings 13 from django.utils.translation import gettext, gettext_lazy,ngettext13 from django.utils.translation import ugettext as _, ugettext_lazy, ungettext 14 14 from django.utils.functional import Promise, lazy 15 from django.utils.encoding import force_unicode 15 16 import re 16 17 … … 33 34 url_re = re.compile(r'^https?://\S+$') 34 35 35 lazy_inter = lazy(lambda a,b: str(a) % b, str)36 lazy_inter = lazy(lambda a,b: force_unicode(a) % b, unicode) 36 37 37 38 class ValidationError(Exception): … … 39 40 "ValidationError can be passed a string or a list." 40 41 if isinstance(message, list): 41 self.messages = message42 self.messages = [force_unicode(msg) for msg in message] 42 43 else: 43 44 assert isinstance(message, (basestring, Promise)), ("%s should be a string" % repr(message)) 44 self.messages = [message] 45 self.messages = [force_unicode(message)] 46 45 47 def __str__(self): 46 48 # This is needed because, without a __str__(), printing an exception … … 54 56 "ValidationError can be passed a string or a list." 55 57 if isinstance(message, list): 56 self.messages = message58 self.messages = [force_unicode(msg) for msg in message] 57 59 else: 58 60 assert isinstance(message, (basestring, Promise)), ("'%s' should be a string" % message) 59 self.messages = [message] 61 self.messages = [force_unicode(message)] 62 60 63 def __str__(self): 61 64 return str(self.messages) … … 63 66 def isAlphaNumeric(field_data, all_data): 64 67 if not alnum_re.search(field_data): 65 raise ValidationError, gettext("This value must contain only letters, numbers and underscores.")68 raise ValidationError, _("This value must contain only letters, numbers and underscores.") 66 69 67 70 def isAlphaNumericURL(field_data, all_data): 68 71 if not alnumurl_re.search(field_data): 69 raise ValidationError, gettext("This value must contain only letters, numbers, underscores, dashes or slashes.")72 raise ValidationError, _("This value must contain only letters, numbers, underscores, dashes or slashes.") 70 73 71 74 def isSlug(field_data, all_data): 72 75 if not slug_re.search(field_data): 73 raise ValidationError, gettext("This value must contain only letters, numbers, underscores or hyphens.")76 raise ValidationError, _("This value must contain only letters, numbers, underscores or hyphens.") 74 77 75 78 def isLowerCase(field_data, all_data): 76 79 if field_data.lower() != field_data: 77 raise ValidationError, gettext("Uppercase letters are not allowed here.")80 raise ValidationError, _("Uppercase letters are not allowed here.") 78 81 79 82 def isUpperCase(field_data, all_data): 80 83 if field_data.upper() != field_data: 81 raise ValidationError, gettext("Lowercase letters are not allowed here.")84 raise ValidationError, _("Lowercase letters are not allowed here.") 82 85 83 86 def isCommaSeparatedIntegerList(field_data, all_data): … … 86 89 int(supposed_int) 87 90 except ValueError: 88 raise ValidationError, gettext("Enter only digits separated by commas.")91 raise ValidationError, _("Enter only digits separated by commas.") 89 92 90 93 def isCommaSeparatedEmailList(field_data, all_data): … … 98 101 isValidEmail(supposed_email.strip(), '') 99 102 except ValidationError: 100 raise ValidationError, gettext("Enter valid e-mail addresses separated by commas.")103 raise ValidationError, _("Enter valid e-mail addresses separated by commas.") 101 104 102 105 def isValidIPAddress4(field_data, all_data): 103 106 if not ip4_re.search(field_data): 104 raise ValidationError, gettext("Please enter a valid IP address.")107 raise ValidationError, _("Please enter a valid IP address.") 105 108 106 109 def isNotEmpty(field_data, all_data): 107 110 if field_data.strip() == '': 108 raise ValidationError, gettext("Empty values are not allowed here.")111 raise ValidationError, _("Empty values are not allowed here.") 109 112 110 113 def isOnlyDigits(field_data, all_data): 111 114 if not field_data.isdigit(): 112 raise ValidationError, gettext("Non-numeric characters aren't allowed here.")115 raise ValidationError, _("Non-numeric characters aren't allowed here.") 113 116 114 117 def isNotOnlyDigits(field_data, all_data): 115 118 if field_data.isdigit(): 116 raise ValidationError, gettext("This value can't be comprised solely of digits.")119 raise ValidationError, _("This value can't be comprised solely of digits.") 117 120 118 121 def isInteger(field_data, all_data): 119 122 # This differs from isOnlyDigits because this accepts the negative sign 120 123 if not integer_re.search(field_data): 121 raise ValidationError, gettext("Enter a whole number.")124 raise ValidationError, _("Enter a whole number.") 122 125 123 126 def isOnlyLetters(field_data, all_data): 124 127 if not field_data.isalpha(): 125 raise ValidationError, gettext("Only alphabetical characters are allowed here.")128 raise ValidationError, _("Only alphabetical characters are allowed here.") 126 129 127 130 def _isValidDate(date_string): … … 138 141 # value to the database, and strftime requires that the year be >=1900. 139 142 if year < 1900: 140 raise ValidationError, gettext('Year must be 1900 or later.')143 raise ValidationError, _('Year must be 1900 or later.') 141 144 try: 142 145 date(year, month, day) 143 146 except ValueError, e: 144 msg = gettext('Invalid date: %s') % gettext(str(e))147 msg = _('Invalid date: %s') % _(str(e)) 145 148 raise ValidationError, msg 146 149 147 150 def isValidANSIDate(field_data, all_data): 148 151 if not ansi_date_re.search(field_data): 149 raise ValidationError, gettext('Enter a valid date in YYYY-MM-DD format.')152 raise ValidationError, _('Enter a valid date in YYYY-MM-DD format.') 150 153 _isValidDate(field_data) 151 154 152 155 def isValidANSITime(field_data, all_data): 153 156 if not ansi_time_re.search(field_data): 154 raise ValidationError, gettext('Enter a valid time in HH:MM format.')157 raise ValidationError, _('Enter a valid time in HH:MM format.') 155 158 156 159 def isValidANSIDatetime(field_data, all_data): 157 160 if not ansi_datetime_re.search(field_data): 158 raise ValidationError, gettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.')161 raise ValidationError, _('Enter a valid date/time in YYYY-MM-DD HH:MM format.') 159 162 _isValidDate(field_data.split()[0]) 160 163 161 164 def isValidEmail(field_data, all_data): 162 165 if not email_re.search(field_data): 163 raise ValidationError, gettext('Enter a valid e-mail address.')166 raise ValidationError, _('Enter a valid e-mail address.') 164 167 165 168 def isValidImage(field_data, all_data): … … 173 176 content = field_data['content'] 174 177 except TypeError: 175 raise ValidationError, gettext("No file was submitted. Check the encoding type on the form.")178 raise ValidationError, _("No file was submitted. Check the encoding type on the form.") 176 179 try: 177 180 Image.open(StringIO(content)) 178 181 except IOError: # Python Imaging Library doesn't recognize it as an image 179 raise ValidationError, gettext("Upload a valid image. The file you uploaded was either not an image or a corrupted image.")182 raise ValidationError, _("Upload a valid image. The file you uploaded was either not an image or a corrupted image.") 180 183 181 184 def isValidImageURL(field_data, all_data): … … 184 187 uc(field_data, all_data) 185 188 except URLMimeTypeCheck.InvalidContentType: 186 raise ValidationError, gettext("The URL %s does not point to a valid image.") % field_data189 raise ValidationError, _("The URL %s does not point to a valid image.") % field_data 187 190 188 191 def isValidPhone(field_data, all_data): 189 192 if not phone_re.search(field_data): 190 raise ValidationError, gettext('Phone numbers must be in XXX-XXX-XXXX format. "%s" is invalid.') % field_data193 raise ValidationError, _('Phone numbers must be in XXX-XXX-XXXX format. "%s" is invalid.') % field_data 191 194 192 195 def isValidQuicktimeVideoURL(field_data, all_data): … … 196 199 uc(field_data, all_data) 197 200 except URLMimeTypeCheck.InvalidContentType: 198 raise ValidationError, gettext("The URL %s does not point to a valid QuickTime video.") % field_data201 raise ValidationError, _("The URL %s does not point to a valid QuickTime video.") % field_data 199 202 200 203 def isValidURL(field_data, all_data): 201 204 if not url_re.search(field_data): 202 raise ValidationError, gettext("A valid URL is required.")205 raise ValidationError, _("A valid URL is required.") 203 206 204 207 def isValidHTML(field_data, all_data): … … 214 217 from xml.dom.minidom import parseString 215 218 error_messages = [e.firstChild.wholeText for e in parseString(u.read()).getElementsByTagName('messages')[0].getElementsByTagName('msg')] 216 raise ValidationError, gettext("Valid HTML is required. Specific errors are:\n%s") % "\n".join(error_messages)219 raise ValidationError, _("Valid HTML is required. Specific errors are:\n%s") % "\n".join(error_messages) 217 220 218 221 def isWellFormedXml(field_data, all_data): … … 221 224 parseString(field_data) 222 225 except Exception, e: # Naked except because we're not sure what will be thrown 223 raise ValidationError, gettext("Badly formed XML: %s") % str(e)226 raise ValidationError, _("Badly formed XML: %s") % str(e) 224 227 225 228 def isWellFormedXmlFragment(field_data, all_data): … … 251 254 states = ['AA', 'AE', 'AK', 'AL', 'AP', 'AR', 'AS', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'FM', 'GA', 'GU', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MH', 'MI', 'MN', 'MO', 'MP', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'PR', 'PW', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VI', 'VT', 'WA', 'WI', 'WV', 'WY'] 252 255 if field_data.upper() not in states: 253 raise ValidationError, gettext("Enter a valid U.S. state abbreviation.")256 raise ValidationError, _("Enter a valid U.S. state abbreviation.") 254 257 255 258 def hasNoProfanities(field_data, all_data): … … 265 268 from django.utils.text import get_text_list 266 269 plural = len(words_seen) > 1 267 raise ValidationError, ngettext("Watch your mouth! The word %s is not allowed here.",270 raise ValidationError, ungettext("Watch your mouth! The word %s is not allowed here.", 268 271 "Watch your mouth! The words %s are not allowed here.", plural) % \ 269 272 get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in words_seen], 'and') … … 272 275 def __init__(self, other_field_name, error_message=None): 273 276 self.other = other_field_name 274 self.error_message = error_message or lazy_inter( gettext_lazy("This field must match the '%s' field."), self.other)277 self.error_message = error_message or lazy_inter(ugettext_lazy("This field must match the '%s' field."), self.other) 275 278 self.always_test = True 276 279 … … 291 294 292 295 class RequiredIfOtherFieldNotGiven(object): 293 def __init__(self, other_field_name, error_message= gettext_lazy("Please enter something for at least one field.")):296 def __init__(self, other_field_name, error_message=ugettext_lazy("Please enter something for at least one field.")): 294 297 self.other, self.error_message = other_field_name, error_message 295 298 self.always_test = True … … 300 303 301 304 class RequiredIfOtherFieldsGiven(object): 302 def __init__(self, other_field_names, error_message= gettext_lazy("Please enter both fields or leave them both empty.")):305 def __init__(self, other_field_names, error_message=ugettext_lazy("Please enter both fields or leave them both empty.")): 303 306 self.other, self.error_message = other_field_names, error_message 304 307 self.always_test = True … … 311 314 class RequiredIfOtherFieldGiven(RequiredIfOtherFieldsGiven): 312 315 "Like RequiredIfOtherFieldsGiven, but takes a single field name instead of a list." 313 def __init__(self, other_field_name, error_message= gettext_lazy("Please enter both fields or leave them both empty.")):316 def __init__(self, other_field_name, error_message=ugettext_lazy("Please enter both fields or leave them both empty.")): 314 317 RequiredIfOtherFieldsGiven.__init__(self, [other_field_name], error_message) 315 318 … … 319 322 self.other_value = other_value 320 323 other_label = other_label or other_value 321 self.error_message = error_message or lazy_inter( gettext_lazy("This field must be given if %(field)s is %(value)s"), {324 self.error_message = error_message or lazy_inter(ugettext_lazy("This field must be given if %(field)s is %(value)s"), { 322 325 'field': other_field, 'value': other_label}) 323 326 self.always_test = True … … 332 335 self.other_value = other_value 333 336 other_label = other_label or other_value 334 self.error_message = error_message or lazy_inter( gettext_lazy("This field must be given if %(field)s is not %(value)s"), {337 self.error_message = error_message or lazy_inter(ugettext_lazy("This field must be given if %(field)s is not %(value)s"), { 335 338 'field': other_field, 'value': other_label}) 336 339 self.always_test = True … … 351 354 def __init__(self, field_name, prefix, error_message): 352 355 self.field_name, self.prefix = field_name, prefix 353 self.error_message = error_message or gettext_lazy("Duplicate values are not allowed.")356 self.error_message = error_message or ugettext_lazy("Duplicate values are not allowed.") 354 357 355 358 def __call__(self, field_data, all_data): … … 366 369 if not error_message: 367 370 if lower and upper: 368 self.error_message = gettext("This value must be between %(lower)s and %(upper)s.") % {'lower': lower, 'upper': upper}371 self.error_message = _("This value must be between %(lower)s and %(upper)s.") % {'lower': lower, 'upper': upper} 369 372 elif lower: 370 self.error_message = gettext("This value must be at least %s.") % lower373 self.error_message = _("This value must be at least %s.") % lower 371 374 elif upper: 372 self.error_message = gettext("This value must be no more than %s.") % upper375 self.error_message = _("This value must be no more than %s.") % upper 373 376 else: 374 377 self.error_message = error_message … … 406 409 val = log(int(field_data)) / log(self.power_of) 407 410 if val != int(val): 408 raise ValidationError, gettext("This value must be a power of %s.") % self.power_of411 raise ValidationError, _("This value must be a power of %s.") % self.power_of 409 412 410 413 class IsValidDecimal(object): … … 415 418 match = decimal_re.search(str(field_data)) 416 419 if not match: 417 raise ValidationError, gettext("Please enter a valid decimal number.")420 raise ValidationError, _("Please enter a valid decimal number.") 418 421 419 422 digits = len(match.group('digits') or '') … … 421 424 422 425 if digits + decimals > self.max_digits: 423 raise ValidationError, ngettext("Please enter a valid decimal number with at most %s total digit.",426 raise ValidationError, ungettext("Please enter a valid decimal number with at most %s total digit.", 424 427 "Please enter a valid decimal number with at most %s total digits.", self.max_digits) % self.max_digits 425 428 if digits > (self.max_digits - self.decimal_places): 426 raise ValidationError, ngettext( "Please enter a valid decimal number with a whole part of at most %s digit.",429 raise ValidationError, ungettext( "Please enter a valid decimal number with a whole part of at most %s digit.", 427 430 "Please enter a valid decimal number with a whole part of at most %s digits.", str(self.max_digits-self.decimal_places)) % str(self.max_digits-self.decimal_places) 428 431 if decimals > self.decimal_places: 429 raise ValidationError, ngettext("Please enter a valid decimal number with at most %s decimal place.",432 raise ValidationError, ungettext("Please enter a valid decimal number with at most %s decimal place.", 430 433 "Please enter a valid decimal number with at most %s decimal places.", self.decimal_places) % self.decimal_places 431 434 … … 435 438 float(data) 436 439 except ValueError: 437 raise ValidationError, gettext("Please enter a valid floating point number.")440 raise ValidationError, ugettext("Please enter a valid floating point number.") 438 441 439 442 class HasAllowableSize(object): … … 444 447 def __init__(self, min_size=None, max_size=None, min_error_message=None, max_error_message=None): 445 448 self.min_size, self.max_size = min_size, max_size 446 self.min_error_message = min_error_message or lazy_inter( gettext_lazy("Make sure your uploaded file is at least %s bytes big."), min_size)447 self.max_error_message = max_error_message or lazy_inter( gettext_lazy("Make sure your uploaded file is at most %s bytes big."), max_size)449 self.min_error_message = min_error_message or lazy_inter(ugettext_lazy("Make sure your uploaded file is at least %s bytes big."), min_size) 450 self.max_error_message = max_error_message or lazy_inter(ugettext_lazy("Make sure your uploaded file is at most %s bytes big."), max_size) 448 451 449 452 def __call__(self, field_data, all_data): … … 451 454 content = field_data['content'] 452 455 except TypeError: 453 raise ValidationError, gettext_lazy("No file was submitted. Check the encoding type on the form.")456 raise ValidationError, ugettext_lazy("No file was submitted. Check the encoding type on the form.") 454 457 if self.min_size is not None and len(content) < self.min_size: 455 458 raise ValidationError, self.min_error_message … … 462 465 should be in string format, not already compiled. 463 466 """ 464 def __init__(self, regexp, error_message= gettext_lazy("The format for this field is wrong.")):467 def __init__(self, regexp, error_message=ugettext_lazy("The format for this field is wrong.")): 465 468 self.regexp = re.compile(regexp) 466 469 self.error_message = error_message … … 477 480 specify one on instantiation. 478 481 """ 479 def __init__(self, validator_list=None, error_message= gettext_lazy("This field is invalid.")):482 def __init__(self, validator_list=None, error_message=ugettext_lazy("This field is invalid.")): 480 483 if validator_list is None: validator_list = [] 481 484 self.validator_list = validator_list … … 513 516 info = urllib2.urlopen(field_data).info() 514 517 except (urllib2.HTTPError, urllib2.URLError): 515 raise URLMimeTypeCheck.CouldNotRetrieve, gettext("Could not retrieve anything from %s.") % field_data518 raise URLMimeTypeCheck.CouldNotRetrieve, _("Could not retrieve anything from %s.") % field_data 516 519 content_type = info['content-type'] 517 520 if content_type not in self.mime_type_list: 518 raise URLMimeTypeCheck.InvalidContentType, gettext("The URL %(url)s returned the invalid Content-Type header '%(contenttype)s'.") % {521 raise URLMimeTypeCheck.InvalidContentType, _("The
