Django

Code

Changeset 5056

Show
Ignore:
Timestamp:
04/21/07 09:34:43 (1 year ago)
Author:
mtredinnick
Message:

Changed default template filters to always return unicode (and to handle unicode input better). Also changed all django.utils.* functions that are used (or likely to be used) by filters to return unicode strings.

Most of the filter porting was done by Ivan Sagalaev. Fixed #3977.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/unicode/django/template/defaultfilters.py

    r4699 r5056  
    33from django.template import resolve_variable, Library 
    44from django.conf import settings 
    5 from django.utils.translation import gettext 
     5from django.utils.translation import ugettext 
     6from django.utils.encoding import smart_unicode, smart_str 
    67import re 
    78import random as random_module 
     
    1314####################### 
    1415 
    15 def smart_string(obj): 
    16     # FUTURE: Unicode strings should probably be normalized to a specific 
    17     # 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 obj 
    26  
    2716def stringfilter(func): 
    2817    """ 
    29     Decorator for filters which should only receive strings. The object passed 
    30     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
    3120    """ 
    3221    def _dec(*args, **kwargs): 
    3322        if args: 
    3423            args = list(args) 
    35             args[0] = smart_string(args[0]) 
     24            args[0] = smart_unicode(args[0]) 
    3625        return func(*args, **kwargs) 
    37          
     26 
    3827    # Include a reference to the real function (used to check original 
    3928    # arguments by the template parser). 
     
    5544    return value and value[0].upper() + value[1:] 
    5645capfirst = stringfilter(capfirst) 
    57   
     46 
    5847def fix_ampersands(value): 
    5948    "Replaces ampersands with ``&`` entities" 
     
    8473        f = float(text) 
    8574    except ValueError: 
    86         return '' 
     75        return u'' 
    8776    try: 
    8877        d = int(arg) 
    8978    except ValueError: 
    90         return smart_string(f) 
     79        return smart_unicode(f) 
    9180    m = f - int(f) 
    9281    if not m and d < 0: 
    93         return '%d' % int(f) 
     82        return u'%d' % int(f) 
    9483    else: 
    95         formatstr = '%%.%df' % abs(d) 
     84        formatstr = u'%%.%df' % abs(d) 
    9685        return formatstr % f 
    9786 
     
    9988    "Displays text with line numbers" 
    10089    from django.utils.html import escape 
    101     lines = value.split('\n') 
     90    lines = value.split(u'\n') 
    10291    # 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)))) 
    10493    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) 
    10796linenumbers = stringfilter(linenumbers) 
    10897 
     
    122111def slugify(value): 
    123112    "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. 
    124114    value = re.sub('[^\w\s-]', '', value).strip().lower() 
    125115    return re.sub('[-\s]+', '-', value) 
     
    136126    """ 
    137127    try: 
    138         return ("%" + str(arg)) % value 
     128        return (u"%" + unicode(arg)) % value 
    139129    except (ValueError, TypeError): 
    140         return "" 
     130        return u"" 
    141131 
    142132def title(value): 
     
    156146    except ValueError: # invalid literal for int() 
    157147        return value # Fail silently. 
    158     if not isinstance(value, basestring): 
    159         value = str(value) 
    160148    return truncate_words(value, length) 
    161149truncatewords = stringfilter(truncatewords) 
     
    172160    except ValueError: # invalid literal for int() 
    173161        return value # Fail silently. 
    174     if not isinstance(value, basestring): 
    175         value = str(value) 
    176162    return truncate_html_words(value, length) 
    177163truncatewords_html = stringfilter(truncatewords_html) 
     
    185171    "Escapes a value for use in a URL" 
    186172    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') 
    190174urlencode = stringfilter(urlencode) 
    191175 
     
    247231def cut(value, arg): 
    248232    "Removes all values of arg from the given string" 
    249     return value.replace(arg, '') 
     233    return value.replace(arg, u'') 
    250234cut = stringfilter(cut) 
    251235 
     
    274258    "Removes a space separated list of [X]HTML tags from the output" 
    275259    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) 
    281265    return value 
    282266removetags = stringfilter(removetags) 
     
    297281    the argument. 
    298282    """ 
    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] 
    300284    decorated.sort() 
    301285    return [item[1] for item in decorated] 
     
    306290    property given in the argument. 
    307291    """ 
    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] 
    309293    decorated.sort() 
    310294    decorated.reverse() 
     
    316300        return value[0] 
    317301    except IndexError: 
    318         return '' 
     302        return u'' 
    319303 
    320304def join(value, arg): 
    321305    "Joins a list with a string, like Python's ``str.join(list)``" 
    322306    try: 
    323         return arg.join(map(smart_string, value)) 
     307        return arg.join(map(smart_unicode, value)) 
    324308    except AttributeError: # fail silently but nicely 
    325309        return value 
     
    347331    try: 
    348332        bits = [] 
    349         for x in arg.split(':'): 
     333        for x in arg.split(u':'): 
    350334            if len(x) == 0: 
    351335                bits.append(None) 
     
    379363    """ 
    380364    def _helper(value, tabs): 
    381         indent = '\t' * tabs 
     365        indent = u'\t' * tabs 
    382366        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) 
    385369        else: 
    386             return '%s<li>%s</li>' % (indent, value[0]) 
     370            return u'%s<li>%s</li>' % (indent, value[0]) 
    387371    return _helper(value, 1) 
    388372 
     
    422406    from django.utils.dateformat import format 
    423407    if not value: 
    424         return '' 
     408        return u'' 
    425409    if arg is None: 
    426410        arg = settings.DATE_FORMAT 
     
    430414    "Formats a time according to the given format" 
    431415    from django.utils.dateformat import time_format 
    432     if value in (None, ''): 
    433         return '' 
     416    if value in (None, u''): 
     417        return u'' 
    434418    if arg is None: 
    435419        arg = settings.TIME_FORMAT 
     
    440424    from django.utils.timesince import timesince 
    441425    if not value: 
    442         return '' 
     426        return u'' 
    443427    if arg: 
    444428        return timesince(arg, value) 
     
    450434    from datetime import datetime 
    451435    if not value: 
    452         return '' 
     436        return u'' 
    453437    if arg: 
    454438        return timesince(arg, value) 
     
    489473    """ 
    490474    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',') 
    493477    if len(bits) < 2: 
    494478        return value # Invalid arg. 
     
    515499        bytes = float(bytes) 
    516500    except TypeError: 
    517         return "0 bytes" 
    518          
     501        return u"0 bytes" 
     502 
    519503    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'') 
    521505    if bytes < 1024 * 1024: 
    522         return "%.1f KB" % (bytes / 1024) 
     506        return u"%.1f KB" % (bytes / 1024) 
    523507    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 
     511def pluralize(value, arg=u's'): 
    528512    """ 
    529513    Returns a plural suffix if the value is not 1, for '1 vote' vs. '2 votes' 
     
    532516    the comma is used for the singular case. 
    533517    """ 
    534     if not ',' in arg: 
    535         arg = ',' + arg 
    536     bits = arg.split(',') 
     518    if not u',' in arg: 
     519        arg = u',' + arg 
     520    bits = arg.split(u',') 
    537521    if len(bits) > 2: 
    538         return '' 
     522        return u'' 
    539523    singular_suffix, plural_suffix = bits[:2] 
    540524 
     
    563547        return pformat(value) 
    564548    except Exception, e: 
    565         return "Error in formatting:%s" % e 
     549        return u"Error in formatting:%s" % e 
    566550 
    567551# Syntax: register.filter(name of filter, callback) 
  • django/branches/unicode/django/utils/dateformat.py

    r4701 r5056  
    1414from django.utils.dates import MONTHS, MONTHS_3, MONTHS_AP, WEEKDAYS 
    1515from django.utils.tzinfo import LocalTimezone 
    16 from django.utils.translation import gettext as _ 
     16from django.utils.translation import ugettext as _ 
    1717from calendar import isleap, monthrange 
    1818import re, time 
     
    2929            elif piece: 
    3030                pieces.append(re_escaped.sub(r'\1', piece)) 
    31         return ''.join(pieces) 
     31        return u''.join(pieces) 
    3232 
    3333class TimeFormat(Formatter): 
     
    5353    def f(self): 
    5454        """ 
    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. 
    5657        Examples: '1', '1:30', '2:05', '2' 
    5758        Proprietary extension. 
     
    5960        if self.data.minute == 0: 
    6061            return self.g() 
    61         return '%s:%s' % (self.g(), self.i()) 
     62        return u'%s:%s' % (self.g(), self.i()) 
    6263 
    6364    def g(self): 
     
    7576    def h(self): 
    7677        "Hour, 12-hour format; i.e. '01' to '12'" 
    77         return '%02d' % self.g() 
     78        return u'%02d' % self.g() 
    7879 
    7980    def H(self): 
    8081        "Hour, 24-hour format; i.e. '00' to '23'" 
    81         return '%02d' % self.G() 
     82        return u'%02d' % self.G() 
    8283 
    8384    def i(self): 
    8485        "Minutes; i.e. '00' to '59'" 
    85         return '%02d' % self.data.minute 
     86        return u'%02d' % self.data.minute 
    8687 
    8788    def P(self): 
     
    9697        if self.data.minute == 0 and self.data.hour == 12: 
    9798            return _('noon') 
    98         return '%s %s' % (self.f(), self.a()) 
     99        return u'%s %s' % (self.f(), self.a()) 
    99100 
    100101    def s(self): 
    101102        "Seconds; i.e. '00' to '59'" 
    102         return '%02d' % self.data.second 
     103        return u'%02d' % self.data.second 
    103104 
    104105class DateFormat(TimeFormat): 
     
    118119    def d(self): 
    119120        "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'" 
    120         return '%02d' % self.data.day 
     121        return u'%02d' % self.data.day 
    121122 
    122123    def D(self): 
     
    131132        "'1' if Daylight Savings Time, '0' otherwise." 
    132133        if self.timezone.dst(self.data): 
    133             return '1' 
     134            return u'1' 
    134135        else: 
    135             return '0' 
     136            return u'0' 
    136137 
    137138    def j(self): 
     
    149150    def m(self): 
    150151        "Month; i.e. '01' to '12'" 
    151         return '%02d' % self.data.month 
     152        return u'%02d' % self.data.month 
    152153 
    153154    def M(self): 
     
    166167        "Difference to Greenwich time in hours; e.g. '+0200'" 
    167168        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) 
    169170 
    170171    def r(self): 
     
    175176        "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'" 
    176177        if self.data.day in (11, 12, 13): # Special case 
    177             return 'th' 
     178            return u'th' 
    178179        last = self.data.day % 10 
    179180        if last == 1: 
    180             return 'st' 
     181            return u'st' 
    181182        if last == 2: 
    182             return 'nd' 
     183            return u'nd' 
    183184        if last == 3: 
    184             return 'rd' 
    185         return 'th' 
     185            return u'rd' 
     186        return u'th' 
    186187 
    187188    def t(self): 
    188189        "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] 
    190191 
    191192    def T(self): 
     
    194195        if name is None: 
    195196            name = self.format('O') 
    196         return name 
     197        return unicode(name) 
    197198 
    198199    def U(self): 
     
    233234    def y(self): 
    234235        "Year, 2 digits; e.g. '99'" 
    235         return str(self.data.year)[2:] 
     236        return unicode(self.data.year)[2:] 
    236237 
    237238    def Y(self): 
  • django/branches/unicode/django/utils/dates.py

    r2912 r5056  
    11"Commonly-used date structures" 
    22 
    3 from django.utils.translation import gettext_lazy as _ 
     3from django.utils.translation import ugettext_lazy as _ 
    44 
    55WEEKDAYS = { 
  • django/branches/unicode/django/utils/html.py

    r4933 r5056  
    2626    "Returns the given HTML with ampersands, quotes and carets encoded" 
    2727    if not isinstance(html, basestring): 
    28         html = str(html) 
     28        html = smart_unicode(html) 
    2929    return html.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;') 
    3030 
     
    3434    paras = re.split('\n{2,}', value) 
    3535    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) 
    3737 
    3838def strip_tags(value): 
     
    8181            if lead + middle + trail != word: 
    8282                words[i] = lead + middle + trail 
    83     return ''.join(words) 
     83    return u''.join(words) 
    8484 
    8585def clean_html(text): 
     
    109109        for d in DOTS: 
    110110            s = s.replace('<p>%s' % d, '<li>') 
    111         return '<ul>\n%s\n</ul>' % s 
     111        return u'<ul>\n%s\n</ul>' % s 
    112112    text = hard_coded_bullets_re.sub(replace_p_tags, text) 
    113113    # Remove stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the bottom of the text. 
  • django/branches/unicode/django/utils/stopwords.py

    r3 r5056  
    3939        if word.lower() not in stopwords: 
    4040            sentence.append(word) 
    41     return ' '.join(sentence) 
     41    return u' '.join(sentence) 
    4242 
  • django/branches/unicode/django/utils/text.py

    r4871 r5056  
    11import re 
    2  
    32from django.conf import settings 
     3from django.utils.encoding import smart_unicode 
    44 
    55# Capitalizes the first letter of a string. 
     
    1111    the text. Expects that existing line breaks are posix newlines. 
    1212    """ 
     13    text = smart_unicode(text) 
    1314    def _generator(): 
    1415        it = iter(text.split(' ')) 
     
    3031                    pos = len(lines[-1]) 
    3132            yield word 
    32     return "".join(_generator()) 
     33    return u''.join(_generator()) 
    3334 
    3435def truncate_words(s, num): 
    3536    "Truncates a string after a certain number of words." 
     37    s = smart_unicode(s) 
    3638    length = int(num) 
    3739    words = s.split() 
     
    4042        if not words[-1].endswith('...'): 
    4143            words.append('...') 
    42     return ' '.join(words) 
     44    return u' '.join(words) 
    4345 
    4446def truncate_html_words(s, num): 
    4547    """ 
    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) 
    4953    length = int(num) 
    5054    if length <= 0: 
    51         return '' 
     55        return u'' 
    5256    html4_singlets = ('br', 'col', 'link', 'base', 'img', 'param', 'area', 'hr', 'input') 
    5357    # Set up regular expressions 
     
    111115    'johns_portrait_in_2004.jpg' 
    112116    """ 
    113     s = s.strip().replace(' ', '_') 
     117    s = smart_unicode(s).strip().replace(' ', '_') 
    114118    return re.sub(r'[^-A-Za-z0-9_.]', '', s) 
    115119 
    116 def get_text_list(list_, last_word='or'): 
     120def get_text_list(list_, last_word=u'or'): 
    117121    """ 
    118122    >>> get_text_list(['a', 'b', 'c', 'd']) 
     
    127131    '' 
    128132    """ 
    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])
    132136 
    133137def 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)
    135139 
    136140def recapitalize(text): 
    137141    "Recapitalizes text, placing caps after end-of-sentence punctuation." 
    138 #     capwords = () 
    139     text = text.lower() 
     142    text = smart_unicode(text).lower() 
    140143    capsRE = re.compile(r'(?:^|(?<=[\.\?\!] ))([a-z])') 
    141144    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) 
    145145    return text 
    146146 
     
    173173 
    174174    if type(s) == str: 
    175         s = s.decode(settings.DEFAULT_CHARSET
     175        s = s.decode('utf-8'
    176176    elif type(s) != unicode: 
    177177        raise TypeError, s 
     
    196196    ['This', 'is', '"a person\'s"', 'test.'] 
    197197    """ 
     198    text = smart_unicode(text) 
    198199    for bit in smart_split_re.finditer(text): 
    199200        bit = bit.group(0) 
  • django/branches/unicode/django/utils/timesince.py

    r3186 r5056  
    11import datetime, math, time 
    22from django.utils.tzinfo import LocalTimezone 
    3 from django.utils.translation import ngettext 
     3from django.utils.translation import ungettext 
    44 
    55def timesince(d, now=None): 
     
    1010    """ 
    1111    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)) 
    1818    ) 
    1919    # Convert datetime.date to datetime.datetime for comparison 
     
    3838            break 
    3939    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)) 
    4242    if i + 1 < len(chunks): 
    4343        # Now get the second item 
  • django/branches/unicode/django/utils/tzinfo.py

    r4265 r5056  
    88    def __init__(self, offset): 
    99        self.__offset = timedelta(minutes=offset) 
    10         self.__name = "%+03d%02d" % (offset // 60, offset % 60) 
     10        self.__name = u"%+03d%02d" % (offset // 60, offset % 60) 
    1111 
    1212    def __repr__(self): 
     
    2626    def __init__(self, dt): 
    2727        tzinfo.__init__(self, dt) 
    28         self._tzname = time.tzname[self._isdst(dt)] 
     28        self._tzname = unicode(time.tzname[self._isdst(dt)]) 
    2929 
    3030    def __repr__(self): 
     
    4444 
    4545    def tzname(self, dt): 
    46         return time.tzname[self._isdst(dt)] 
     46        return unicode(time.tzname[self._isdst(dt)]) 
    4747 
    4848    def _isdst(self, dt): 
  • django/branches/unicode/tests/regressiontests/dateformat/tests.py

    r4647 r5056  
    11r""" 
    22>>> format(my_birthday, '') 
    3 '' 
     3u'' 
    44>>> format(my_birthday, 'a') 
    5 'p.m.' 
     5u'p.m.' 
    66>>> format(my_birthday, 'A') 
    7 'PM' 
     7u'PM' 
    88>>> format(my_birthday, 'd') 
    9 '08' 
     9u'08' 
    1010>>> format(my_birthday, 'j') 
    11 '8' 
     11u'8' 
    1212>>> format(my_birthday, 'l') 
    13 'Sunday' 
     13u'Sunday' 
    1414>>> format(my_birthday, 'L') 
    15 'False' 
     15u'False' 
    1616>>> format(my_birthday, 'm') 
    17 '07' 
     17u'07' 
    1818>>> format(my_birthday, 'M') 
    19 'Jul' 
     19u'Jul' 
    2020>>> format(my_birthday, 'b') 
    21 'jul' 
     21u'jul' 
    2222>>> format(my_birthday, 'n') 
    23 '7' 
     23u'7' 
    2424>>> format(my_birthday, 'N') 
    25 'July' 
     25u'July' 
    2626>>> no_tz or format(my_birthday, 'O') == '+0100' 
    2727True 
    2828>>> format(my_birthday, 'P') 
    29 '10 p.m.' 
     29u'10 p.m.' 
    3030>>> no_tz or format(my_birthday, 'r') == 'Sun, 8 Jul 1979 22:00:00 +0100' 
    3131True 
    3232>>> format(my_birthday, 's') 
    33 '00' 
     33u'00' 
    3434>>> format(my_birthday, 'S') 
    35 'th' 
     35u'th' 
    3636>>> format(my_birthday, 't') 
    37 '31' 
     37u'31' 
    3838>>> no_tz or format(my_birthday, 'T') == 'CET' 
    3939True 
     
    4141True 
    4242>>> format(my_birthday, 'w') 
    43 '0' 
     43u'0' 
    4444>>> format(my_birthday, 'W') 
    45 '27' 
     45u'27' 
    4646>>> format(my_birthday, 'y') 
    47 '79' 
     47u'79' 
    4848>>> format(my_birthday, 'Y') 
    49 '1979' 
     49u'1979' 
    5050>>> format(my_birthday, 'z') 
    51 '189' 
     51u'189' 
    5252>>> no_tz or format(my_birthday, 'Z') == '3600' 
    5353True 
     
    6363 
    6464>>> format(my_birthday, r'Y z \C\E\T') 
    65 '1979 189 CET' 
     65u'1979 189 CET' 
    6666 
    6767>>> format(my_birthday, r'jS o\f F') 
    68 '8th of July' 
     68u'8th of July' 
    6969""" 
    7070 
  • django/branches/unicode/tests/regressiontests/defaultfilters/tests.py

    r4919 r5056  
    33r""" 
    44>>> floatformat(7.7) 
    5 '7.7' 
     5u'7.7' 
    66>>> floatformat(7.0) 
    7 '7' 
     7u'7' 
    88>>> floatformat(0.7) 
    9 '0.7' 
     9u'0.7' 
    1010>>> floatformat(0.07) 
    11 '0.1' 
     11u'0.1' 
    1212>>> floatformat(0.007) 
    13 '0.0' 
     13u'0.0' 
    1414>>> floatformat(0.0) 
    15 '0' 
     15u'0' 
    1616>>> floatformat(7.7,3) 
    17 '7.700' 
     17u'7.700' 
    1818>>> floatformat(6.000000,3) 
    19 '6.000' 
     19u'6.000' 
    2020>>> floatformat(13.1031,-3) 
    21 '13.103' 
     21u'13.103' 
    2222>>> floatformat(11.1197, -2) 
    23 '11.12' 
     23u'11.12' 
    2424>>> floatformat(11.0000, -2) 
    25 '11' 
     25u'11' 
    2626>>> floatformat(11.000001, -2) 
    27 '11.00' 
     27u'11.00' 
    2828>>> 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 &amp; Jill &amp; 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' 
     29u'8.280' 
     30>>> floatformat(u'foo') 
     31u'' 
     32>>> floatformat(13.1031, u'bar') 
     33u'13.1031' 
     34>>> floatformat(u'foo', u'bar') 
     35u'' 
     36 
     37>>> addslashes(u'"double quotes" and \'single quotes\'') 
     38u'\\"double quotes\\" and \\\'single quotes\\\'' 
     39 
     40>>> addslashes(ur'\ : backslashes, too') 
     41u'\\\\ : backslashes, too' 
     42 
     43>>> capfirst(u'hello world') 
     44u'Hello world' 
     45 
     46>>> fix_ampersands(u'Jack & Jill & Jeroboam') 
     47u'Jack &amp; Jill &amp; Jeroboam' 
     48 
     49>>> linenumbers(u'line 1\nline 2') 
     50u'1. line 1\n2. line 2' 
     51 
     52>>> linenumbers(u'\n'.join([u'x'] * 10)) 
     53u'01. x\n02. x\n03. x\n04. x\n05. x\n06. x\n07. x\n08. x\n09. x\n10. x' 
    5454 
    5555>>> lower('TEST') 
    56 'test' 
     56u'test' 
    5757 
    5858>>> lower(u'\xcb') # uppercase E umlaut 
     
    6060 
    6161>>> make_list('abc') 
    62 ['a', 'b', 'c'] 
     62[u'a', u'b', u'c'] 
    6363 
    6464>>> make_list(1234) 
    65 ['1', '2', '3', '4'] 
     65[u'1', u'2', u'3', u'4'] 
    6666 
    6767>>> 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 '' 
     68u'jack-jill-like-numbers-123-and-4-and-silly-characters' 
     69 
     70>>> stringformat(1, u'03d') 
     71u'001' 
     72 
     73>>> stringformat(1, u'z') 
     74u'' 
    7575 
    7676>>> 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' 
     77u"A Nice Title, Isn't It?" 
     78 
     79 
     80>>> truncatewords(u'A sentence with a few words in it', 1) 
     81u'A ...' 
     82 
     83>>> truncatewords(u'A sentence with a few words in it', 5) 
     84u'A sentence with a few ...' 
     85 
     86>>> truncatewords(u'A sentence with a few words in it', 100) 
     87u'A sentence with a few words in it' 
     88 
     89>>> truncatewords(u'A sentence with a few words in it', 'not a number') 
     90u'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) 
     93u'' 
     94 
     95>>> truncatewords_html(u'<p>one <a href="#">two - three <br>four</a> five</p>', 2) 
     96u'<p>one <a href="#">two ...</a></p>' 
     97 
     98>>> truncatewords_html(u'<p>one <a href="#">two - three <br>four</a> five</p>', 4) 
     99u'<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) 
     102u'<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) 
     105u'<p>one <a href="#">two - three <br>four</a> five</p>' 
     106 
     107>>> upper(u'Mixed case input') 
     108u'MIXED CASE INPUT' 
    109109 
    110110>>> upper(u'\xeb') # lowercase e umlaut 
     
    112112 
    113113 
    114 >>> urlencode('jack & jill') 
    115 'jack%20%26%20jill' 
     114>>> urlencode(u'jack & jill') 
     115u'jack%20%26%20jill' 
    116116>>> 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('') 
     117u'1' 
     118 
     119 
     120>>> urlizetrunc(u'http://short.com/', 20) 
     121u'<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) 
     124u'<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'') 
    1271270 
    128128 
    129 >>> wordcount('oneword') 
     129>>> wordcount(u'oneword') 
    1301301 
    131131 
    132 >>> wordcount('lots of words') 
     132>>> wordcount(u'lots of words') 
    1331333 
    134134 
    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 <