Ticket #3977: 3977.diff

File 3977.diff, 26.5 KB (added by Ivan Sagalaev <Maniac@…>, 17 years ago)

Patch

  • django/template/defaultfilters.py

     
    33from django.template import resolve_variable, Library
    44from django.conf import settings
    55from django.utils.translation import gettext
     6from django.utils.encoding import smart_unicode, smart_str
    67import re
    78import random as random_module
    89
     
    1213# STRING DECORATOR    #
    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)
    3726       
    3827    # Include a reference to the real function (used to check original
     
    8372    try:
    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
    9887def linenumbers(value):
    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
    10998def lower(value):
     
    121110
    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)
    126116slugify = stringfilter(slugify)
     
    135125    of Python string formatting
    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):
    143133    "Converts a string into titlecase"
     
    155145        length = int(arg)
    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)
    162150
     
    171159        length = int(arg)
    172160    except ValueError: # invalid literal for int()
    173161        return value # Fail silently.
    174     if not isinstance(value, basestring):
    175         value = str(value)
    176     return truncate_html_words(value, length)
     162    result = truncate_html_words(value, length)
     163    # isagalaev: Actually the better solution would be converting text utils to output unicode
     164    if isinstance(result, str):
     165      result = result.decode('utf-8')
     166    return result
    177167truncatewords_html = stringfilter(truncatewords_html)
    178168
    179169def upper(value):
     
    184174def urlencode(value):
    185175    "Escapes a value for use in a URL"
    186176    import urllib
    187     if not isinstance(value, basestring):
    188         value = str(value)
    189     return urllib.quote(value)
     177    return urllib.quote(value).decode('utf-8')
    190178urlencode = stringfilter(urlencode)
    191179
    192180def urlize(value):
     
    246234
    247235def cut(value, arg):
    248236    "Removes all values of arg from the given string"
    249     return value.replace(arg, '')
     237    return value.replace(arg, u'')
    250238cut = stringfilter(cut)
    251239
    252240###################
     
    273261def removetags(value, tags):
    274262    "Removes a space separated list of [X]HTML tags from the output"
    275263    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)
     264    tags_re = u'(%s)' % u'|'.join(tags)
     265    starttag_re = re.compile(ur'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U)
     266    endtag_re = re.compile(u'</%s>' % tags_re, re.U)
     267    value = starttag_re.sub(u'', value)
     268    value = endtag_re.sub(u'', value)
    281269    return value
    282270removetags = stringfilter(removetags)
    283271
     
    296284    Takes a list of dicts, returns that list sorted by the property given in
    297285    the argument.
    298286    """
    299     decorated = [(resolve_variable('var.' + arg, {'var' : item}), item) for item in value]
     287    decorated = [(resolve_variable(u'var.' + arg, {u'var' : item}), item) for item in value]
    300288    decorated.sort()
    301289    return [item[1] for item in decorated]
    302290
     
    305293    Takes a list of dicts, returns that list sorted in reverse order by the
    306294    property given in the argument.
    307295    """
    308     decorated = [(resolve_variable('var.' + arg, {'var' : item}), item) for item in value]
     296    decorated = [(resolve_variable(u'var.' + arg, {u'var' : item}), item) for item in value]
    309297    decorated.sort()
    310298    decorated.reverse()
    311299    return [item[1] for item in decorated]
     
    315303    try:
    316304        return value[0]
    317305    except IndexError:
    318         return ''
     306        return u''
    319307
    320308def join(value, arg):
    321309    "Joins a list with a string, like Python's ``str.join(list)``"
    322310    try:
    323         return arg.join(map(smart_string, value))
     311        return arg.join(map(smart_unicode, value))
    324312    except AttributeError: # fail silently but nicely
    325313        return value
    326314
     
    346334    """
    347335    try:
    348336        bits = []
    349         for x in arg.split(':'):
     337        for x in arg.split(u':'):
    350338            if len(x) == 0:
    351339                bits.append(None)
    352340            else:
     
    378366        </li>
    379367    """
    380368    def _helper(value, tabs):
    381         indent = '\t' * tabs
     369        indent = u'\t' * tabs
    382370        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)
     371            return u'%s<li>%s\n%s<ul>\n%s\n%s</ul>\n%s</li>' % (indent, value[0], indent,
     372                u'\n'.join([_helper(v, tabs+1) for v in value[1]]), indent, indent)
    385373        else:
    386             return '%s<li>%s</li>' % (indent, value[0])
     374            return u'%s<li>%s</li>' % (indent, value[0])
    387375    return _helper(value, 1)
    388376
    389377###################
     
    409397    if arg < 1:
    410398        return value
    411399    try:
    412         return int(str(value)[-arg])
     400        return int(smart_unicode(value)[-arg])
    413401    except IndexError:
    414402        return 0
    415403
     
    421409    "Formats a date according to the given format"
    422410    from django.utils.dateformat import format
    423411    if not value:
    424         return ''
     412        return u''
    425413    if arg is None:
    426414        arg = settings.DATE_FORMAT
    427     return format(value, arg)
     415    else:
     416        arg = smart_str(arg)
     417    # isagalaev: Actually the better solution would be converting dateformat utils to deal with unicode
     418    return format(value, arg).decode('utf-8')
    428419
    429420def time(value, arg=None):
    430421    "Formats a time according to the given format"
    431422    from django.utils.dateformat import time_format
    432     if value in (None, ''):
    433         return ''
     423    if value in (None, u''):
     424        return u''
    434425    if arg is None:
    435426        arg = settings.TIME_FORMAT
    436     return time_format(value, arg)
     427    else:
     428        arg = smart_str(arg)
     429    # isagalaev: Actually the better solution would be converting dateformat utils to deal with unicode
     430    return time_format(value, arg).decode('utf-8')
    437431
    438432def timesince(value, arg=None):
    439433    'Formats a date as the time since that date (i.e. "4 days, 6 hours")'
    440434    from django.utils.timesince import timesince
    441435    if not value:
    442         return ''
     436        return u''
    443437    if arg:
    444         return timesince(arg, value)
    445     return timesince(value)
     438        return timesince(arg, value).decode('utf-8')
     439    return timesince(value).decode('utf-8')
    446440
    447441def timeuntil(value, arg=None):
    448442    'Formats a date as the time until that date (i.e. "4 days, 6 hours")'
    449443    from django.utils.timesince import timesince
    450444    from datetime import datetime
    451445    if not value:
    452         return ''
     446        return u''
     447    # isagalaev: Actually the better solution would be converting timesince utils to deal with unicode
    453448    if arg:
    454         return timesince(arg, value)
    455     return timesince(datetime.now(), value)
     449        return timesince(arg, value).decode('utf-8')
     450    return timesince(datetime.now(), value).decode('utf-8')
    456451
    457452###################
    458453# LOGIC           #
     
    488483    ==========  ======================  ==================================
    489484    """
    490485    if arg is None:
    491         arg = gettext('yes,no,maybe')
    492     bits = arg.split(',')
     486        arg = gettext('yes,no,maybe').decode('utf-8')
     487    bits = arg.split(u',')
    493488    if len(bits) < 2:
    494489        return value # Invalid arg.
    495490    try:
     
    514509    try:
    515510        bytes = float(bytes)
    516511    except TypeError:
    517         return "0 bytes"
     512        return u"0 bytes"
    518513       
    519514    if bytes < 1024:
    520         return "%d byte%s" % (bytes, bytes != 1 and 's' or '')
     515        return u"%d byte%s" % (bytes, bytes != 1 and u's' or u'')
    521516    if bytes < 1024 * 1024:
    522         return "%.1f KB" % (bytes / 1024)
     517        return u"%.1f KB" % (bytes / 1024)
    523518    if bytes < 1024 * 1024 * 1024:
    524         return "%.1f MB" % (bytes / (1024 * 1024))
    525     return "%.1f GB" % (bytes / (1024 * 1024 * 1024))
     519        return u"%.1f MB" % (bytes / (1024 * 1024))
     520    return u"%.1f GB" % (bytes / (1024 * 1024 * 1024))
    526521
    527 def pluralize(value, arg='s'):
     522def pluralize(value, arg=u's'):
    528523    """
    529524    Returns a plural suffix if the value is not 1, for '1 vote' vs. '2 votes'
    530525    By default, 's' is used as a suffix; if an argument is provided, that string
    531526    is used instead. If the provided argument contains a comma, the text before
    532527    the comma is used for the singular case.
    533528    """
    534     if not ',' in arg:
    535         arg = ',' + arg
    536     bits = arg.split(',')
     529    if not u',' in arg:
     530        arg = u',' + arg
     531    bits = arg.split(u',')
    537532    if len(bits) > 2:
    538         return ''
     533        return u''
    539534    singular_suffix, plural_suffix = bits[:2]
    540535
    541536    try:
     
    554549def phone2numeric(value):
    555550    "Takes a phone number and converts it in to its numerical equivalent"
    556551    from django.utils.text import phone2numeric
    557     return phone2numeric(value)
     552    # isagalaev: Actually the better solution would be converting text utils to return unicode
     553    return phone2numeric(value).decode('utf-8')
    558554
    559555def pprint(value):
    560556    "A wrapper around pprint.pprint -- for debugging, really"
     
    562558    try:
    563559        return pformat(value)
    564560    except Exception, e:
    565         return "Error in formatting:%s" % e
     561        return u"Error in formatting:%s" % e
    566562
    567563# Syntax: register.filter(name of filter, callback)
    568564register.filter(add)
  • tests/regressiontests/defaultfilters/tests.py

     
    22
    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 ''
     29u'8.280'
     30>>> floatformat(u'foo')
     31u''
     32>>> floatformat(13.1031, u'bar')
     33u'13.1031'
     34>>> floatformat(u'foo', u'bar')
     35u''
    3636
    37 >>> addslashes('"double quotes" and \'single quotes\'')
    38 '\\"double quotes\\" and \\\'single quotes\\\''
     37>>> addslashes(u'"double quotes" and \'single quotes\'')
     38u'\\"double quotes\\" and \\\'single quotes\\\''
    3939
    40 >>> addslashes(r'\ : backslashes, too')
    41 '\\\\ : backslashes, too'
     40>>> addslashes(ur'\ : backslashes, too')
     41u'\\\\ : backslashes, too'
    4242
    43 >>> capfirst('hello world')
    44 'Hello world'
     43>>> capfirst(u'hello world')
     44u'Hello world'
    4545
    46 >>> fix_ampersands('Jack & Jill & Jeroboam')
    47 'Jack &amp; Jill &amp; Jeroboam'
     46>>> fix_ampersands(u'Jack & Jill & Jeroboam')
     47u'Jack &amp; Jill &amp; Jeroboam'
    4848
    49 >>> linenumbers('line 1\nline 2')
    50 '1. line 1\n2. line 2'
     49>>> linenumbers(u'line 1\nline 2')
     50u'1. line 1\n2. line 2'
    5151
    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'
     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
    5959u'\xeb'
    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'
     68u'jack-jill-like-numbers-123-and-4-and-silly-characters'
    6969
    70 >>> stringformat(1, '03d')
    71 '001'
     70>>> stringformat(1, u'03d')
     71u'001'
    7272
    73 >>> stringformat(1, 'z')
    74 ''
     73>>> stringformat(1, u'z')
     74u''
    7575
    7676>>> title('a nice title, isn\'t it?')
    77 "A Nice Title, Isn't It?"
     77u"A Nice Title, Isn't It?"
    7878
    7979
    80 >>> truncatewords('A sentence with a few words in it', 1)
    81 'A ...'
     80>>> truncatewords(u'A sentence with a few words in it', 1)
     81u'A ...'
    8282
    83 >>> truncatewords('A sentence with a few words in it', 5)
    84 'A sentence with a few ...'
     83>>> truncatewords(u'A sentence with a few words in it', 5)
     84u'A sentence with a few ...'
    8585
    86 >>> truncatewords('A sentence with a few words in it', 100)
    87 'A sentence with a few words in it'
     86>>> truncatewords(u'A sentence with a few words in it', 100)
     87u'A sentence with a few words in it'
    8888
    89 >>> truncatewords('A sentence with a few words in it', 'not a number')
    90 'A sentence with a few words in it'
     89>>> truncatewords(u'A sentence with a few words in it', 'not a number')
     90u'A sentence with a few words in it'
    9191
    92 >>> truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 0)
    93 ''
     92>>> truncatewords_html(u'<p>one <a href="#">two - three <br>four</a> five</p>', 0)
     93u''
    9494
    95 >>> truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 2)
    96 '<p>one <a href="#">two ...</a></p>'
     95>>> truncatewords_html(u'<p>one <a href="#">two - three <br>four</a> five</p>', 2)
     96u'<p>one <a href="#">two ...</a></p>'
    9797
    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>'
     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>'
    100100
    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>'
     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>'
    103103
    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>'
     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>'
    106106
    107 >>> upper('Mixed case input')
    108 'MIXED CASE INPUT'
     107>>> upper(u'Mixed case input')
     108u'MIXED CASE INPUT'
    109109
    110110>>> upper(u'\xeb') # lowercase e umlaut
    111111u'\xcb'
    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'
     117u'1'
    118118
    119119
    120 >>> urlizetrunc('http://short.com/', 20)
    121 '<a href="http://short.com/" rel="nofollow">http://short.com/</a>'
     120>>> urlizetrunc(u'http://short.com/', 20)
     121u'<a href="http://short.com/" rel="nofollow">http://short.com/</a>'
    122122
    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>'
     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>'
    125125
    126 >>> wordcount('')
     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"
     135>>> wordwrap(u'this is a long paragraph of text that really needs to be wrapped I\'m afraid', 14)
     136u"this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI'm afraid"
    137137
    138 >>> wordwrap('this is a short paragraph of text.\n  But this line should be indented',14)
    139 'this is a\nshort\nparagraph of\ntext.\n  But this\nline should be\nindented'
     138>>> wordwrap(u'this is a short paragraph of text.\n  But this line should be indented',14)
     139u'this is a\nshort\nparagraph of\ntext.\n  But this\nline should be\nindented'
    140140
    141 >>> wordwrap('this is a short paragraph of text.\n  But this line should be indented',15)
    142 'this is a short\nparagraph of\ntext.\n  But this line\nshould be\nindented'
     141>>> wordwrap(u'this is a short paragraph of text.\n  But this line should be indented',15)
     142u'this is a short\nparagraph of\ntext.\n  But this line\nshould be\nindented'
    143143
    144 >>> ljust('test', 10)
    145 'test      '
     144>>> ljust(u'test', 10)
     145u'test      '
    146146
    147 >>> ljust('test', 3)
    148 'test'
     147>>> ljust(u'test', 3)
     148u'test'
    149149
    150 >>> rjust('test', 10)
    151 '      test'
     150>>> rjust(u'test', 10)
     151u'      test'
    152152
    153 >>> rjust('test', 3)
    154 'test'
     153>>> rjust(u'test', 3)
     154u'test'
    155155
    156 >>> center('test', 6)
    157 ' test '
     156>>> center(u'test', 6)
     157u' test '
    158158
    159 >>> cut('a string to be mangled', 'a')
    160 ' string to be mngled'
     159>>> cut(u'a string to be mangled', 'a')
     160u' string to be mngled'
    161161
    162 >>> cut('a string to be mangled', 'ng')
    163 'a stri to be maled'
     162>>> cut(u'a string to be mangled', 'ng')
     163u'a stri to be maled'
    164164
    165 >>> cut('a string to be mangled', 'strings')
    166 'a string to be mangled'
     165>>> cut(u'a string to be mangled', 'strings')
     166u'a string to be mangled'
    167167
    168 >>> escape('<some html & special characters > here')
    169 '&lt;some html &amp; special characters &gt; here'
     168>>> escape(u'<some html & special characters > here')
     169u'&lt;some html &amp; special characters &gt; here'
    170170
    171171>>> escape(u'<some html & special characters > here ĐÅ€£')
    172172u'&lt;some html &amp; special characters &gt; here \xc4\x90\xc3\x85\xe2\x82\xac\xc2\xa3'
    173173
    174 >>> linebreaks('line 1')
    175 '<p>line 1</p>'
     174>>> linebreaks(u'line 1')
     175u'<p>line 1</p>'
    176176
    177 >>> linebreaks('line 1\nline 2')
    178 '<p>line 1<br />line 2</p>'
     177>>> linebreaks(u'line 1\nline 2')
     178u'<p>line 1<br />line 2</p>'
    179179
    180 >>> removetags('some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags', 'script img')
    181 'some <b>html</b> with alert("You smell") disallowed  tags'
     180>>> removetags(u'some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags', 'script img')
     181u'some <b>html</b> with alert("You smell") disallowed  tags'
    182182
    183 >>> striptags('some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags')
    184 'some html with alert("You smell") disallowed  tags'
     183>>> striptags(u'some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags')
     184u'some html with alert("You smell") disallowed  tags'
    185185
    186186>>> dictsort([{'age': 23, 'name': 'Barbara-Ann'},
    187187...           {'age': 63, 'name': 'Ra Ra Rasputin'},
     
    196196>>> first([0,1,2])
    1971970
    198198
    199 >>> first('')
    200 ''
     199>>> first(u'')
     200u''
    201201
    202 >>> first('test')
    203 't'
     202>>> first(u'test')
     203u't'
    204204
    205 >>> join([0,1,2], 'glue')
    206 '0glue1glue2'
     205>>> join([0,1,2], u'glue')
     206u'0glue1glue2'
    207207
    208 >>> length('1234')
     208>>> length(u'1234')
    2092094
    210210
    211211>>> length([1,2,3,4])
     
    220220>>> length_is('a', 1)
    221221True
    222222
    223 >>> length_is('a', 10)
     223>>> length_is(u'a', 10)
    224224False
    225225
    226 >>> slice_('abcdefg', '0')
    227 ''
     226>>> slice_(u'abcdefg', u'0')
     227u''
    228228
    229 >>> slice_('abcdefg', '1')
    230 'a'
     229>>> slice_(u'abcdefg', u'1')
     230u'a'
    231231
    232 >>> slice_('abcdefg', '-1')
    233 'abcdef'
     232>>> slice_(u'abcdefg', u'-1')
     233u'abcdef'
    234234
    235 >>> slice_('abcdefg', '1:2')
    236 'b'
     235>>> slice_(u'abcdefg', u'1:2')
     236u'b'
    237237
    238 >>> slice_('abcdefg', '1:3')
    239 'bc'
     238>>> slice_(u'abcdefg', u'1:3')
     239u'bc'
    240240
    241 >>> slice_('abcdefg', '0::2')
    242 'aceg'
     241>>> slice_(u'abcdefg', u'0::2')
     242u'aceg'
    243243
    244 >>> unordered_list(['item 1', []])
    245 '\t<li>item 1</li>'
     244>>> unordered_list([u'item 1', []])
     245u'\t<li>item 1</li>'
    246246
    247 >>> unordered_list(['item 1', [['item 1.1', []]]])
    248 '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>'
     247>>> unordered_list([u'item 1', [[u'item 1.1', []]]])
     248u'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>'
    249249
    250 >>> unordered_list(['item 1', [['item 1.1', []], ['item 1.2', []]]])
    251 '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t\t<li>item 1.2</li>\n\t</ul>\n\t</li>'
     250>>> unordered_list([u'item 1', [[u'item 1.1', []], [u'item 1.2', []]]])
     251u'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t\t<li>item 1.2</li>\n\t</ul>\n\t</li>'
    252252
    253 >>> add('1', '2')
     253>>> add(u'1', u'2')
    2542543
    255255
    256256>>> get_digit(123, 1)
     
    268268>>> get_digit(123, 0)
    269269123
    270270
    271 >>> get_digit('xyz', 0)
    272 'xyz'
     271>>> get_digit(u'xyz', 0)
     272u'xyz'
    273273
    274274# real testing of date() is in dateformat.py
    275 >>> date(datetime.datetime(2005, 12, 29), "d F Y")
    276 '29 December 2005'
    277 >>> date(datetime.datetime(2005, 12, 29), r'jS o\f F')
    278 '29th of December'
     275>>> date(datetime.datetime(2005, 12, 29), u"d F Y")
     276u'29 December 2005'
     277>>> date(datetime.datetime(2005, 12, 29), ur'jS o\f F')
     278u'29th of December'
    279279
    280280# real testing of time() is done in dateformat.py
    281 >>> time(datetime.time(13), "h")
    282 '01'
     281>>> time(datetime.time(13), u"h")
     282u'01'
    283283
    284 >>> time(datetime.time(0), "h")
    285 '12'
     284>>> time(datetime.time(0), u"h")
     285u'12'
    286286
    287287# real testing is done in timesince.py, where we can provide our own 'now'
    288288>>> timesince(datetime.datetime.now() - datetime.timedelta(1))
    289 '1 day'
     289u'1 day'
    290290
    291 >>> default("val", "default")
    292 'val'
     291>>> default(u"val", u"default")
     292u'val'
    293293
    294 >>> default(None, "default")
    295 'default'
     294>>> default(None, u"default")
     295u'default'
    296296
    297 >>> default('', "default")
    298 'default'
     297>>> default(u'', u"default")
     298u'default'
    299299
    300 >>> default_if_none("val", "default")
    301 'val'
     300>>> default_if_none(u"val", u"default")
     301u'val'
    302302
    303 >>> default_if_none(None, "default")
    304 'default'
     303>>> default_if_none(None, u"default")
     304u'default'
    305305
    306 >>> default_if_none('', "default")
    307 ''
     306>>> default_if_none(u'', u"default")
     307u''
    308308
    309309>>> divisibleby(4, 2)
    310310True
     
    313313False
    314314
    315315>>> yesno(True)
    316 'yes'
     316u'yes'
    317317
    318318>>> yesno(False)
    319 'no'
     319u'no'
    320320
    321321>>> yesno(None)
    322 'maybe'
     322u'maybe'
    323323
    324 >>> yesno(True, 'certainly,get out of town,perhaps')
    325 'certainly'
     324>>> yesno(True, u'certainly,get out of town,perhaps')
     325u'certainly'
    326326
    327 >>> yesno(False, 'certainly,get out of town,perhaps')
    328 'get out of town'
     327>>> yesno(False, u'certainly,get out of town,perhaps')
     328u'get out of town'
    329329
    330 >>> yesno(None, 'certainly,get out of town,perhaps')
    331 'perhaps'
     330>>> yesno(None, u'certainly,get out of town,perhaps')
     331u'perhaps'
    332332
    333 >>> yesno(None, 'certainly,get out of town')
    334 'get out of town'
     333>>> yesno(None, u'certainly,get out of town')
     334u'get out of town'
    335335
    336336>>> filesizeformat(1023)
    337 '1023 bytes'
     337u'1023 bytes'
    338338
    339339>>> filesizeformat(1024)
    340 '1.0 KB'
     340u'1.0 KB'
    341341
    342342>>> filesizeformat(10*1024)
    343 '10.0 KB'
     343u'10.0 KB'
    344344
    345345>>> filesizeformat(1024*1024-1)
    346 '1024.0 KB'
     346u'1024.0 KB'
    347347
    348348>>> filesizeformat(1024*1024)
    349 '1.0 MB'
     349u'1.0 MB'
    350350
    351351>>> filesizeformat(1024*1024*50)
    352 '50.0 MB'
     352u'50.0 MB'
    353353
    354354>>> filesizeformat(1024*1024*1024-1)
    355 '1024.0 MB'
     355u'1024.0 MB'
    356356
    357357>>> filesizeformat(1024*1024*1024)
    358 '1.0 GB'
     358u'1.0 GB'
    359359
    360360>>> pluralize(1)
    361 ''
     361u''
    362362
    363363>>> pluralize(0)
    364 's'
     364u's'
    365365
    366366>>> pluralize(2)
    367 's'
     367u's'
    368368
    369369>>> pluralize([1])
    370 ''
     370u''
    371371
    372372>>> pluralize([])
    373 's'
     373u's'
    374374
    375375>>> pluralize([1,2,3])
    376 's'
     376u's'
    377377
    378 >>> pluralize(1,'es')
    379 ''
     378>>> pluralize(1,u'es')
     379u''
    380380
    381 >>> pluralize(0,'es')
    382 'es'
     381>>> pluralize(0,u'es')
     382u'es'
    383383
    384 >>> pluralize(2,'es')
    385 'es'
     384>>> pluralize(2,u'es')
     385u'es'
    386386
    387 >>> pluralize(1,'y,ies')
    388 'y'
     387>>> pluralize(1,u'y,ies')
     388u'y'
    389389
    390 >>> pluralize(0,'y,ies')
    391 'ies'
     390>>> pluralize(0,u'y,ies')
     391u'ies'
    392392
    393 >>> pluralize(2,'y,ies')
    394 'ies'
     393>>> pluralize(2,u'y,ies')
     394u'ies'
    395395
    396 >>> pluralize(0,'y,ies,error')
    397 ''
     396>>> pluralize(0,u'y,ies,error')
     397u''
    398398
    399 >>> phone2numeric('0800 flowers')
    400 '0800 3569377'
     399>>> phone2numeric(u'0800 flowers')
     400u'0800 3569377'
    401401
    402402# Filters shouldn't break if passed non-strings
    403403>>> addslashes(123)
    404 '123'
     404u'123'
    405405>>> linenumbers(123)
    406 '1. 123'
     406u'1. 123'
    407407>>> lower(123)
    408 '123'
     408u'123'
    409409>>> make_list(123)
    410 ['1', '2', '3']
     410[u'1', u'2', u'3']
    411411>>> slugify(123)
    412 '123'
     412u'123'
    413413>>> title(123)
    414 '123'
     414u'123'
    415415>>> truncatewords(123, 2)
    416 '123'
     416u'123'
    417417>>> upper(123)
    418 '123'
     418u'123'
    419419>>> urlencode(123)
    420 '123'
     420u'123'
    421421>>> urlize(123)
    422 '123'
     422u'123'
    423423>>> urlizetrunc(123, 1)
    424 '123'
     424u'123'
    425425>>> wordcount(123)
    4264261
    427427>>> wordwrap(123, 2)
    428 '123'
     428u'123'
    429429>>> ljust('123', 4)
    430 '123 '
     430u'123 '
    431431>>> rjust('123', 4)
    432 ' 123'
     432u' 123'
    433433>>> center('123', 5)
    434 ' 123 '
     434u' 123 '
    435435>>> center('123', 6)
    436 ' 123  '
     436u' 123  '
    437437>>> cut(123, '2')
    438 '13'
     438u'13'
    439439>>> escape(123)
    440 '123'
     440u'123'
    441441>>> linebreaks(123)
    442 '<p>123</p>'
     442u'<p>123</p>'
    443443>>> linebreaksbr(123)
    444 '123'
     444u'123'
    445445>>> removetags(123, 'a')
    446 '123'
     446u'123'
    447447>>> striptags(123)
    448 '123'
     448u'123'
    449449
    450450"""
    451451
Back to Top