Changeset 5056
- Timestamp:
- 04/21/07 09:34:43 (1 year ago)
- Files:
-
- django/branches/unicode/django/template/defaultfilters.py (modified) (25 diffs)
- django/branches/unicode/django/utils/dateformat.py (modified) (13 diffs)
- django/branches/unicode/django/utils/dates.py (modified) (1 diff)
- django/branches/unicode/django/utils/html.py (modified) (4 diffs)
- django/branches/unicode/django/utils/stopwords.py (modified) (1 diff)
- django/branches/unicode/django/utils/text.py (modified) (8 diffs)
- django/branches/unicode/django/utils/timesince.py (modified) (3 diffs)
- django/branches/unicode/django/utils/tzinfo.py (modified) (3 diffs)
- django/branches/unicode/tests/regressiontests/dateformat/tests.py (modified) (3 diffs)
- django/branches/unicode/tests/regressiontests/defaultfilters/tests.py (modified) (7 diffs)
- django/branches/unicode/tests/regressiontests/text/tests.py (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/branches/unicode/django/template/defaultfilters.py
r4699 r5056 3 3 from django.template import resolve_variable, Library 4 4 from django.conf import settings 5 from django.utils.translation import gettext 5 from django.utils.translation import ugettext 6 from django.utils.encoding import smart_unicode, smart_str 6 7 import re 7 8 import random as random_module … … 13 14 ####################### 14 15 15 def smart_string(obj):16 # FUTURE: Unicode strings should probably be normalized to a specific17 # encoding and non-unicode strings should be converted to unicode too.18 # if isinstance(obj, unicode):19 # obj = obj.encode(settings.DEFAULT_CHARSET)20 # else:21 # obj = unicode(obj, settings.DEFAULT_CHARSET)22 # FUTURE: Replace dumb string logic below with cool unicode logic above.23 if not isinstance(obj, basestring):24 obj = str(obj)25 return obj26 27 16 def stringfilter(func): 28 17 """ 29 Decorator for filters which should only receive strings. The object passed30 as the first positional argument will be converted to a string.18 Decorator for filters which should only receive unicode objects. The object passed 19 as the first positional argument will be converted to a unicode object. 31 20 """ 32 21 def _dec(*args, **kwargs): 33 22 if args: 34 23 args = list(args) 35 args[0] = smart_ string(args[0])24 args[0] = smart_unicode(args[0]) 36 25 return func(*args, **kwargs) 37 26 38 27 # Include a reference to the real function (used to check original 39 28 # arguments by the template parser). … … 55 44 return value and value[0].upper() + value[1:] 56 45 capfirst = stringfilter(capfirst) 57 46 58 47 def fix_ampersands(value): 59 48 "Replaces ampersands with ``&`` entities" … … 84 73 f = float(text) 85 74 except ValueError: 86 return ''75 return u'' 87 76 try: 88 77 d = int(arg) 89 78 except ValueError: 90 return smart_ string(f)79 return smart_unicode(f) 91 80 m = f - int(f) 92 81 if not m and d < 0: 93 return '%d' % int(f)82 return u'%d' % int(f) 94 83 else: 95 formatstr = '%%.%df' % abs(d)84 formatstr = u'%%.%df' % abs(d) 96 85 return formatstr % f 97 86 … … 99 88 "Displays text with line numbers" 100 89 from django.utils.html import escape 101 lines = value.split( '\n')90 lines = value.split(u'\n') 102 91 # Find the maximum width of the line count, for use with zero padding string format command 103 width = str(len(str(len(lines))))92 width = unicode(len(unicode(len(lines)))) 104 93 for i, line in enumerate(lines): 105 lines[i] = ( "%0" + width +"d. %s") % (i + 1, escape(line))106 return '\n'.join(lines)94 lines[i] = (u"%0" + width + u"d. %s") % (i + 1, escape(line)) 95 return u'\n'.join(lines) 107 96 linenumbers = stringfilter(linenumbers) 108 97 … … 122 111 def slugify(value): 123 112 "Converts to lowercase, removes non-alpha chars and converts spaces to hyphens" 113 # Don't compile patterns as unicode because \w then would mean any letter. Slugify is effectively an asciiization. 124 114 value = re.sub('[^\w\s-]', '', value).strip().lower() 125 115 return re.sub('[-\s]+', '-', value) … … 136 126 """ 137 127 try: 138 return ( "%" + str(arg)) % value128 return (u"%" + unicode(arg)) % value 139 129 except (ValueError, TypeError): 140 return ""130 return u"" 141 131 142 132 def title(value): … … 156 146 except ValueError: # invalid literal for int() 157 147 return value # Fail silently. 158 if not isinstance(value, basestring):159 value = str(value)160 148 return truncate_words(value, length) 161 149 truncatewords = stringfilter(truncatewords) … … 172 160 except ValueError: # invalid literal for int() 173 161 return value # Fail silently. 174 if not isinstance(value, basestring):175 value = str(value)176 162 return truncate_html_words(value, length) 177 163 truncatewords_html = stringfilter(truncatewords_html) … … 185 171 "Escapes a value for use in a URL" 186 172 import urllib 187 if not isinstance(value, basestring): 188 value = str(value) 189 return urllib.quote(value) 173 return urllib.quote(value).decode('utf-8') 190 174 urlencode = stringfilter(urlencode) 191 175 … … 247 231 def cut(value, arg): 248 232 "Removes all values of arg from the given string" 249 return value.replace(arg, '')233 return value.replace(arg, u'') 250 234 cut = stringfilter(cut) 251 235 … … 274 258 "Removes a space separated list of [X]HTML tags from the output" 275 259 tags = [re.escape(tag) for tag in tags.split()] 276 tags_re = '(%s)' %'|'.join(tags)277 starttag_re = re.compile( r'<%s(/?>|(\s+[^>]*>))' % tags_re)278 endtag_re = re.compile( '</%s>' % tags_re)279 value = starttag_re.sub( '', value)280 value = endtag_re.sub( '', value)260 tags_re = u'(%s)' % u'|'.join(tags) 261 starttag_re = re.compile(ur'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U) 262 endtag_re = re.compile(u'</%s>' % tags_re) 263 value = starttag_re.sub(u'', value) 264 value = endtag_re.sub(u'', value) 281 265 return value 282 266 removetags = stringfilter(removetags) … … 297 281 the argument. 298 282 """ 299 decorated = [(resolve_variable( 'var.' + arg, {'var' : item}), item) for item in value]283 decorated = [(resolve_variable(u'var.' + arg, {u'var' : item}), item) for item in value] 300 284 decorated.sort() 301 285 return [item[1] for item in decorated] … … 306 290 property given in the argument. 307 291 """ 308 decorated = [(resolve_variable( 'var.' + arg, {'var' : item}), item) for item in value]292 decorated = [(resolve_variable(u'var.' + arg, {u'var' : item}), item) for item in value] 309 293 decorated.sort() 310 294 decorated.reverse() … … 316 300 return value[0] 317 301 except IndexError: 318 return ''302 return u'' 319 303 320 304 def join(value, arg): 321 305 "Joins a list with a string, like Python's ``str.join(list)``" 322 306 try: 323 return arg.join(map(smart_ string, value))307 return arg.join(map(smart_unicode, value)) 324 308 except AttributeError: # fail silently but nicely 325 309 return value … … 347 331 try: 348 332 bits = [] 349 for x in arg.split( ':'):333 for x in arg.split(u':'): 350 334 if len(x) == 0: 351 335 bits.append(None) … … 379 363 """ 380 364 def _helper(value, tabs): 381 indent = '\t' * tabs365 indent = u'\t' * tabs 382 366 if value[1]: 383 return '%s<li>%s\n%s<ul>\n%s\n%s</ul>\n%s</li>' % (indent, value[0], indent,384 '\n'.join([_helper(v, tabs+1) for v in value[1]]), indent, indent)367 return u'%s<li>%s\n%s<ul>\n%s\n%s</ul>\n%s</li>' % (indent, value[0], indent, 368 u'\n'.join([_helper(v, tabs+1) for v in value[1]]), indent, indent) 385 369 else: 386 return '%s<li>%s</li>' % (indent, value[0])370 return u'%s<li>%s</li>' % (indent, value[0]) 387 371 return _helper(value, 1) 388 372 … … 422 406 from django.utils.dateformat import format 423 407 if not value: 424 return ''408 return u'' 425 409 if arg is None: 426 410 arg = settings.DATE_FORMAT … … 430 414 "Formats a time according to the given format" 431 415 from django.utils.dateformat import time_format 432 if value in (None, ''):433 return ''416 if value in (None, u''): 417 return u'' 434 418 if arg is None: 435 419 arg = settings.TIME_FORMAT … … 440 424 from django.utils.timesince import timesince 441 425 if not value: 442 return ''426 return u'' 443 427 if arg: 444 428 return timesince(arg, value) … … 450 434 from datetime import datetime 451 435 if not value: 452 return ''436 return u'' 453 437 if arg: 454 438 return timesince(arg, value) … … 489 473 """ 490 474 if arg is None: 491 arg = gettext('yes,no,maybe')492 bits = arg.split( ',')475 arg = ugettext('yes,no,maybe') 476 bits = arg.split(u',') 493 477 if len(bits) < 2: 494 478 return value # Invalid arg. … … 515 499 bytes = float(bytes) 516 500 except TypeError: 517 return "0 bytes"518 501 return u"0 bytes" 502 519 503 if bytes < 1024: 520 return "%d byte%s" % (bytes, bytes != 1 and 's' or'')504 return u"%d byte%s" % (bytes, bytes != 1 and u's' or u'') 521 505 if bytes < 1024 * 1024: 522 return "%.1f KB" % (bytes / 1024)506 return u"%.1f KB" % (bytes / 1024) 523 507 if bytes < 1024 * 1024 * 1024: 524 return "%.1f MB" % (bytes / (1024 * 1024))525 return "%.1f GB" % (bytes / (1024 * 1024 * 1024))526 527 def pluralize(value, arg= 's'):508 return u"%.1f MB" % (bytes / (1024 * 1024)) 509 return u"%.1f GB" % (bytes / (1024 * 1024 * 1024)) 510 511 def pluralize(value, arg=u's'): 528 512 """ 529 513 Returns a plural suffix if the value is not 1, for '1 vote' vs. '2 votes' … … 532 516 the comma is used for the singular case. 533 517 """ 534 if not ',' in arg:535 arg = ',' + arg536 bits = arg.split( ',')518 if not u',' in arg: 519 arg = u',' + arg 520 bits = arg.split(u',') 537 521 if len(bits) > 2: 538 return ''522 return u'' 539 523 singular_suffix, plural_suffix = bits[:2] 540 524 … … 563 547 return pformat(value) 564 548 except Exception, e: 565 return "Error in formatting:%s" % e549 return u"Error in formatting:%s" % e 566 550 567 551 # Syntax: register.filter(name of filter, callback) django/branches/unicode/django/utils/dateformat.py
r4701 r5056 14 14 from django.utils.dates import MONTHS, MONTHS_3, MONTHS_AP, WEEKDAYS 15 15 from django.utils.tzinfo import LocalTimezone 16 from django.utils.translation import gettext as _16 from django.utils.translation import ugettext as _ 17 17 from calendar import isleap, monthrange 18 18 import re, time … … 29 29 elif piece: 30 30 pieces.append(re_escaped.sub(r'\1', piece)) 31 return ''.join(pieces)31 return u''.join(pieces) 32 32 33 33 class TimeFormat(Formatter): … … 53 53 def f(self): 54 54 """ 55 Time, in 12-hour hours and minutes, with minutes left off if they're zero. 55 Time, in 12-hour hours and minutes, with minutes left off if they're 56 zero. 56 57 Examples: '1', '1:30', '2:05', '2' 57 58 Proprietary extension. … … 59 60 if self.data.minute == 0: 60 61 return self.g() 61 return '%s:%s' % (self.g(), self.i())62 return u'%s:%s' % (self.g(), self.i()) 62 63 63 64 def g(self): … … 75 76 def h(self): 76 77 "Hour, 12-hour format; i.e. '01' to '12'" 77 return '%02d' % self.g()78 return u'%02d' % self.g() 78 79 79 80 def H(self): 80 81 "Hour, 24-hour format; i.e. '00' to '23'" 81 return '%02d' % self.G()82 return u'%02d' % self.G() 82 83 83 84 def i(self): 84 85 "Minutes; i.e. '00' to '59'" 85 return '%02d' % self.data.minute86 return u'%02d' % self.data.minute 86 87 87 88 def P(self): … … 96 97 if self.data.minute == 0 and self.data.hour == 12: 97 98 return _('noon') 98 return '%s %s' % (self.f(), self.a())99 return u'%s %s' % (self.f(), self.a()) 99 100 100 101 def s(self): 101 102 "Seconds; i.e. '00' to '59'" 102 return '%02d' % self.data.second103 return u'%02d' % self.data.second 103 104 104 105 class DateFormat(TimeFormat): … … 118 119 def d(self): 119 120 "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'" 120 return '%02d' % self.data.day121 return u'%02d' % self.data.day 121 122 122 123 def D(self): … … 131 132 "'1' if Daylight Savings Time, '0' otherwise." 132 133 if self.timezone.dst(self.data): 133 return '1'134 return u'1' 134 135 else: 135 return '0'136 return u'0' 136 137 137 138 def j(self): … … 149 150 def m(self): 150 151 "Month; i.e. '01' to '12'" 151 return '%02d' % self.data.month152 return u'%02d' % self.data.month 152 153 153 154 def M(self): … … 166 167 "Difference to Greenwich time in hours; e.g. '+0200'" 167 168 tz = self.timezone.utcoffset(self.data) 168 return "%+03d%02d" % (tz.seconds // 3600, (tz.seconds // 60) % 60)169 return u"%+03d%02d" % (tz.seconds // 3600, (tz.seconds // 60) % 60) 169 170 170 171 def r(self): … … 175 176 "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'" 176 177 if self.data.day in (11, 12, 13): # Special case 177 return 'th'178 return u'th' 178 179 last = self.data.day % 10 179 180 if last == 1: 180 return 'st'181 return u'st' 181 182 if last == 2: 182 return 'nd'183 return u'nd' 183 184 if last == 3: 184 return 'rd'185 return 'th'185 return u'rd' 186 return u'th' 186 187 187 188 def t(self): 188 189 "Number of days in the given month; i.e. '28' to '31'" 189 return '%02d' % monthrange(self.data.year, self.data.month)[1]190 return u'%02d' % monthrange(self.data.year, self.data.month)[1] 190 191 191 192 def T(self): … … 194 195 if name is None: 195 196 name = self.format('O') 196 return name197 return unicode(name) 197 198 198 199 def U(self): … … 233 234 def y(self): 234 235 "Year, 2 digits; e.g. '99'" 235 return str(self.data.year)[2:]236 return unicode(self.data.year)[2:] 236 237 237 238 def Y(self): django/branches/unicode/django/utils/dates.py
r2912 r5056 1 1 "Commonly-used date structures" 2 2 3 from django.utils.translation import gettext_lazy as _3 from django.utils.translation import ugettext_lazy as _ 4 4 5 5 WEEKDAYS = { django/branches/unicode/django/utils/html.py
r4933 r5056 26 26 "Returns the given HTML with ampersands, quotes and carets encoded" 27 27 if not isinstance(html, basestring): 28 html = s tr(html)28 html = smart_unicode(html) 29 29 return html.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''') 30 30 … … 34 34 paras = re.split('\n{2,}', value) 35 35 paras = ['<p>%s</p>' % p.strip().replace('\n', '<br />') for p in paras] 36 return '\n\n'.join(paras)36 return u'\n\n'.join(paras) 37 37 38 38 def strip_tags(value): … … 81 81 if lead + middle + trail != word: 82 82 words[i] = lead + middle + trail 83 return ''.join(words)83 return u''.join(words) 84 84 85 85 def clean_html(text): … … 109 109 for d in DOTS: 110 110 s = s.replace('<p>%s' % d, '<li>') 111 return '<ul>\n%s\n</ul>' % s111 return u'<ul>\n%s\n</ul>' % s 112 112 text = hard_coded_bullets_re.sub(replace_p_tags, text) 113 113 # Remove stuff like "<p> </p>", but only if it's at the bottom of the text. django/branches/unicode/django/utils/stopwords.py
r3 r5056 39 39 if word.lower() not in stopwords: 40 40 sentence.append(word) 41 return ' '.join(sentence)41 return u' '.join(sentence) 42 42 django/branches/unicode/django/utils/text.py
r4871 r5056 1 1 import re 2 3 2 from django.conf import settings 3 from django.utils.encoding import smart_unicode 4 4 5 5 # Capitalizes the first letter of a string. … … 11 11 the text. Expects that existing line breaks are posix newlines. 12 12 """ 13 text = smart_unicode(text) 13 14 def _generator(): 14 15 it = iter(text.split(' ')) … … 30 31 pos = len(lines[-1]) 31 32 yield word 32 return "".join(_generator())33 return u''.join(_generator()) 33 34 34 35 def truncate_words(s, num): 35 36 "Truncates a string after a certain number of words." 37 s = smart_unicode(s) 36 38 length = int(num) 37 39 words = s.split() … … 40 42 if not words[-1].endswith('...'): 41 43 words.append('...') 42 return ' '.join(words)44 return u' '.join(words) 43 45 44 46 def truncate_html_words(s, num): 45 47 """ 46 Truncates html to a certain number of words (not counting tags and comments). 47 Closes opened tags if they were correctly closed in the given html. 48 """ 48 Truncates html to a certain number of words (not counting tags and 49 comments). Closes opened tags if they were correctly closed in the given 50 html. 51 """ 52 s = smart_unicode(s) 49 53 length = int(num) 50 54 if length <= 0: 51 return ''55 return u'' 52 56 html4_singlets = ('br', 'col', 'link', 'base', 'img', 'param', 'area', 'hr', 'input') 53 57 # Set up regular expressions … … 111 115 'johns_portrait_in_2004.jpg' 112 116 """ 113 s = s .strip().replace(' ', '_')117 s = smart_unicode(s).strip().replace(' ', '_') 114 118 return re.sub(r'[^-A-Za-z0-9_.]', '', s) 115 119 116 def get_text_list(list_, last_word= 'or'):120 def get_text_list(list_, last_word=u'or'): 117 121 """ 118 122 >>> get_text_list(['a', 'b', 'c', 'd']) … … 127 131 '' 128 132 """ 129 if len(list_) == 0: return ''130 if len(list_) == 1: return list_[0]131 return '%s %s %s' % (', '.join([str(i) for i in list_][:-1]), last_word, list_[-1])133 if len(list_) == 0: return u'' 134 if len(list_) == 1: return smart_unicode(list_[0]) 135 return u'%s %s %s' % (', '.join([smart_unicode(i) for i in list_][:-1]), smart_unicode(last_word), smart_unicode(list_[-1])) 132 136 133 137 def normalize_newlines(text): 134 return re.sub(r'\r\n|\r|\n', '\n', text)138 return smart_unicode(re.sub(r'\r\n|\r|\n', '\n', text)) 135 139 136 140 def recapitalize(text): 137 141 "Recapitalizes text, placing caps after end-of-sentence punctuation." 138 # capwords = () 139 text = text.lower() 142 text = smart_unicode(text).lower() 140 143 capsRE = re.compile(r'(?:^|(?<=[\.\?\!] ))([a-z])') 141 144 text = capsRE.sub(lambda x: x.group(1).upper(), text) 142 # for capword in capwords:143 # capwordRE = re.compile(r'\b%s\b' % capword, re.I)144 # text = capwordRE.sub(capword, text)145 145 return text 146 146 … … 173 173 174 174 if type(s) == str: 175 s = s.decode( settings.DEFAULT_CHARSET)175 s = s.decode('utf-8') 176 176 elif type(s) != unicode: 177 177 raise TypeError, s … … 196 196 ['This', 'is', '"a person\'s"', 'test.'] 197 197 """ 198 text = smart_unicode(text) 198 199 for bit in smart_split_re.finditer(text): 199 200 bit = bit.group(0) django/branches/unicode/django/utils/timesince.py
r3186 r5056 1 1 import datetime, math, time 2 2 from django.utils.tzinfo import LocalTimezone 3 from django.utils.translation import ngettext3 from django.utils.translation import ungettext 4 4 5 5 def timesince(d, now=None): … … 10 10 """ 11 11 chunks = ( 12 (60 * 60 * 24 * 365, lambda n: ngettext('year', 'years', n)),13 (60 * 60 * 24 * 30, lambda n: ngettext('month', 'months', n)),14 (60 * 60 * 24 * 7, lambda n : ngettext('week', 'weeks', n)),15 (60 * 60 * 24, lambda n : ngettext('day', 'days', n)),16 (60 * 60, lambda n: ngettext('hour', 'hours', n)),17 (60, lambda n: ngettext('minute', 'minutes', n))12 (60 * 60 * 24 * 365, lambda n: ungettext('year', 'years', n)), 13 (60 * 60 * 24 * 30, lambda n: ungettext('month', 'months', n)), 14 (60 * 60 * 24 * 7, lambda n : ungettext('week', 'weeks', n)), 15 (60 * 60 * 24, lambda n : ungettext('day', 'days', n)), 16 (60 * 60, lambda n: ungettext('hour', 'hours', n)), 17 (60, lambda n: ungettext('minute', 'minutes', n)) 18 18 ) 19 19 # Convert datetime.date to datetime.datetime for comparison … … 38 38 break 39 39 if count < 0: 40 return '%d milliseconds' % math.floor((now - d).microseconds / 1000)41 s = '%d %s' % (count, name(count))40 return u'%d milliseconds' % math.floor((now - d).microseconds / 1000) 41 s = u'%d %s' % (count, name(count)) 42 42 if i + 1 < len(chunks): 43 43 # Now get the second item django/branches/unicode/django/utils/tzinfo.py
r4265 r5056 8 8 def __init__(self, offset): 9 9 self.__offset = timedelta(minutes=offset) 10 self.__name = "%+03d%02d" % (offset // 60, offset % 60)10 self.__name = u"%+03d%02d" % (offset // 60, offset % 60) 11 11 12 12 def __repr__(self): … … 26 26 def __init__(self, dt): 27 27 tzinfo.__init__(self, dt) 28 self._tzname = time.tzname[self._isdst(dt)]28 self._tzname = unicode(time.tzname[self._isdst(dt)]) 29 29 30 30 def __repr__(self): … … 44 44 45 45 def tzname(self, dt): 46 return time.tzname[self._isdst(dt)]46 return unicode(time.tzname[self._isdst(dt)]) 47 47 48 48 def _isdst(self, dt): django/branches/unicode/tests/regressiontests/dateformat/tests.py
r4647 r5056 1 1 r""" 2 2 >>> format(my_birthday, '') 3 ''3 u'' 4 4 >>> format(my_birthday, 'a') 5 'p.m.'5 u'p.m.' 6 6 >>> format(my_birthday, 'A') 7 'PM'7 u'PM' 8 8 >>> format(my_birthday, 'd') 9 '08'9 u'08' 10 10 >>> format(my_birthday, 'j') 11 '8'11 u'8' 12 12 >>> format(my_birthday, 'l') 13 'Sunday'13 u'Sunday' 14 14 >>> format(my_birthday, 'L') 15 'False'15 u'False' 16 16 >>> format(my_birthday, 'm') 17 '07'17 u'07' 18 18 >>> format(my_birthday, 'M') 19 'Jul'19 u'Jul' 20 20 >>> format(my_birthday, 'b') 21 'jul'21 u'jul' 22 22 >>> format(my_birthday, 'n') 23 '7'23 u'7' 24 24 >>> format(my_birthday, 'N') 25 'July'25 u'July' 26 26 >>> no_tz or format(my_birthday, 'O') == '+0100' 27 27 True 28 28 >>> format(my_birthday, 'P') 29 '10 p.m.'29 u'10 p.m.' 30 30 >>> no_tz or format(my_birthday, 'r') == 'Sun, 8 Jul 1979 22:00:00 +0100' 31 31 True 32 32 >>> format(my_birthday, 's') 33 '00'33 u'00' 34 34 >>> format(my_birthday, 'S') 35 'th'35 u'th' 36 36 >>> format(my_birthday, 't') 37 '31'37 u'31' 38 38 >>> no_tz or format(my_birthday, 'T') == 'CET' 39 39 True … … 41 41 True 42 42 >>> format(my_birthday, 'w') 43 '0'43 u'0' 44 44 >>> format(my_birthday, 'W') 45 '27'45 u'27' 46 46 >>> format(my_birthday, 'y') 47 '79'47 u'79' 48 48 >>> format(my_birthday, 'Y') 49 '1979'49 u'1979' 50 50 >>> format(my_birthday, 'z') 51 '189'51 u'189' 52 52 >>> no_tz or format(my_birthday, 'Z') == '3600' 53 53 True … … 63 63 64 64 >>> format(my_birthday, r'Y z \C\E\T') 65 '1979 189 CET'65 u'1979 189 CET' 66 66 67 67 >>> format(my_birthday, r'jS o\f F') 68 '8th of July'68 u'8th of July' 69 69 """ 70 70 django/branches/unicode/tests/regressiontests/defaultfilters/tests.py
r4919 r5056 3 3 r""" 4 4 >>> floatformat(7.7) 5 '7.7'5 u'7.7' 6 6 >>> floatformat(7.0) 7 '7'7 u'7' 8 8 >>> floatformat(0.7) 9 '0.7'9 u'0.7' 10 10 >>> floatformat(0.07) 11 '0.1'11 u'0.1' 12 12 >>> floatformat(0.007) 13 '0.0'13 u'0.0' 14 14 >>> floatformat(0.0) 15 '0'15 u'0' 16 16 >>> floatformat(7.7,3) 17 '7.700'17 u'7.700' 18 18 >>> floatformat(6.000000,3) 19 '6.000'19 u'6.000' 20 20 >>> floatformat(13.1031,-3) 21 '13.103'21 u'13.103' 22 22 >>> floatformat(11.1197, -2) 23 '11.12'23 u'11.12' 24 24 >>> floatformat(11.0000, -2) 25 '11'25 u'11' 26 26 >>> floatformat(11.000001, -2) 27 '11.00'27 u'11.00' 28 28 >>> floatformat(8.2798, 3) 29 '8.280'30 >>> floatformat( 'foo')31 ''32 >>> floatformat(13.1031, 'bar')33 '13.1031'34 >>> floatformat( 'foo','bar')35 ''36 37 >>> addslashes( '"double quotes" and \'single quotes\'')38 '\\"double quotes\\" and \\\'single quotes\\\''39 40 >>> addslashes( r'\ : backslashes, too')41 '\\\\ : backslashes, too'42 43 >>> capfirst( 'hello world')44 'Hello world'45 46 >>> fix_ampersands( 'Jack & Jill & Jeroboam')47 'Jack & Jill & Jeroboam'48 49 >>> linenumbers( 'line 1\nline 2')50 '1. line 1\n2. line 2'51 52 >>> linenumbers( '\n'.join(['x'] * 10))53 '01. x\n02. x\n03. x\n04. x\n05. x\n06. x\n07. x\n08. x\n09. x\n10. x'29 u'8.280' 30 >>> floatformat(u'foo') 31 u'' 32 >>> floatformat(13.1031, u'bar') 33 u'13.1031' 34 >>> floatformat(u'foo', u'bar') 35 u'' 36 37 >>> addslashes(u'"double quotes" and \'single quotes\'') 38 u'\\"double quotes\\" and \\\'single quotes\\\'' 39 40 >>> addslashes(ur'\ : backslashes, too') 41 u'\\\\ : backslashes, too' 42 43 >>> capfirst(u'hello world') 44 u'Hello world' 45 46 >>> fix_ampersands(u'Jack & Jill & Jeroboam') 47 u'Jack & Jill & Jeroboam' 48 49 >>> linenumbers(u'line 1\nline 2') 50 u'1. line 1\n2. line 2' 51 52 >>> linenumbers(u'\n'.join([u'x'] * 10)) 53 u'01. x\n02. x\n03. x\n04. x\n05. x\n06. x\n07. x\n08. x\n09. x\n10. x' 54 54 55 55 >>> lower('TEST') 56 'test'56 u'test' 57 57 58 58 >>> lower(u'\xcb') # uppercase E umlaut … … 60 60 61 61 >>> make_list('abc') 62 [ 'a', 'b','c']62 [u'a', u'b', u'c'] 63 63 64 64 >>> make_list(1234) 65 [ '1', '2', '3','4']65 [u'1', u'2', u'3', u'4'] 66 66 67 67 >>> slugify(' Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/') 68 'jack-jill-like-numbers-123-and-4-and-silly-characters'69 70 >>> stringformat(1, '03d')71 '001'72 73 >>> stringformat(1, 'z')74 ''68 u'jack-jill-like-numbers-123-and-4-and-silly-characters' 69 70 >>> stringformat(1, u'03d') 71 u'001' 72 73 >>> stringformat(1, u'z') 74 u'' 75 75 76 76 >>> title('a nice title, isn\'t it?') 77 "A Nice Title, Isn't It?"78 79 80 >>> truncatewords( 'A sentence with a few words in it', 1)81 'A ...'82 83 >>> truncatewords( 'A sentence with a few words in it', 5)84 'A sentence with a few ...'85 86 >>> truncatewords( 'A sentence with a few words in it', 100)87 'A sentence with a few words in it'88 89 >>> truncatewords( 'A sentence with a few words in it', 'not a number')90 'A sentence with a few words in it'91 92 >>> truncatewords_html( '<p>one <a href="#">two - three <br>four</a> five</p>', 0)93 ''94 95 >>> truncatewords_html( '<p>one <a href="#">two - three <br>four</a> five</p>', 2)96 '<p>one <a href="#">two ...</a></p>'97 98 >>> truncatewords_html( '<p>one <a href="#">two - three <br>four</a> five</p>', 4)99 '<p>one <a href="#">two - three <br>four ...</a></p>'100 101 >>> truncatewords_html( '<p>one <a href="#">two - three <br>four</a> five</p>', 5)102 '<p>one <a href="#">two - three <br>four</a> five</p>'103 104 >>> truncatewords_html( '<p>one <a href="#">two - three <br>four</a> five</p>', 100)105 '<p>one <a href="#">two - three <br>four</a> five</p>'106 107 >>> upper( 'Mixed case input')108 'MIXED CASE INPUT'77 u"A Nice Title, Isn't It?" 78 79 80 >>> truncatewords(u'A sentence with a few words in it', 1) 81 u'A ...' 82 83 >>> truncatewords(u'A sentence with a few words in it', 5) 84 u'A sentence with a few ...' 85 86 >>> truncatewords(u'A sentence with a few words in it', 100) 87 u'A sentence with a few words in it' 88 89 >>> truncatewords(u'A sentence with a few words in it', 'not a number') 90 u'A sentence with a few words in it' 91 92 >>> truncatewords_html(u'<p>one <a href="#">two - three <br>four</a> five</p>', 0) 93 u'' 94 95 >>> truncatewords_html(u'<p>one <a href="#">two - three <br>four</a> five</p>', 2) 96 u'<p>one <a href="#">two ...</a></p>' 97 98 >>> truncatewords_html(u'<p>one <a href="#">two - three <br>four</a> five</p>', 4) 99 u'<p>one <a href="#">two - three <br>four ...</a></p>' 100 101 >>> truncatewords_html(u'<p>one <a href="#">two - three <br>four</a> five</p>', 5) 102 u'<p>one <a href="#">two - three <br>four</a> five</p>' 103 104 >>> truncatewords_html(u'<p>one <a href="#">two - three <br>four</a> five</p>', 100) 105 u'<p>one <a href="#">two - three <br>four</a> five</p>' 106 107 >>> upper(u'Mixed case input') 108 u'MIXED CASE INPUT' 109 109 110 110 >>> upper(u'\xeb') # lowercase e umlaut … … 112 112 113 113 114 >>> urlencode( 'jack & jill')115 'jack%20%26%20jill'114 >>> urlencode(u'jack & jill') 115 u'jack%20%26%20jill' 116 116 >>> urlencode(1) 117 '1'118 119 120 >>> urlizetrunc( 'http://short.com/', 20)121 '<a href="http://short.com/" rel="nofollow">http://short.com/</a>'122 123 >>> urlizetrunc( 'http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=', 20)124 '<a href="http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=" rel="nofollow">http://www.google.co...</a>'125 126 >>> wordcount( '')117 u'1' 118 119 120 >>> urlizetrunc(u'http://short.com/', 20) 121 u'<a href="http://short.com/" rel="nofollow">http://short.com/</a>' 122 123 >>> urlizetrunc(u'http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=', 20) 124 u'<a href="http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=" rel="nofollow">http://www.google.co...</a>' 125 126 >>> wordcount(u'') 127 127 0 128 128 129 >>> wordcount( 'oneword')129 >>> wordcount(u'oneword') 130 130 1 131 131 132 >>> wordcount( 'lots of words')132 >>> wordcount(u'lots of words') 133 133 3 134 134 135 >>> wordwrap( 'this is a long paragraph of text that really needs to be wrapped I\'m afraid', 14)136 "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI'm afraid"137 138 >>> wordwrap( 'this is a short paragraph of text.\n But this line should be indented',14)139 <
