To Truncate a Word to # of chars

1 view
Skip to first unread message

Siah

unread,
Feb 26, 2006, 3:36:13 PM2/26/06
to Django users
Hi,

I noticed there is no filter to truncate a string to a given number of
characters as apposed to just words. It can be useful. For instance I
am trying to show contact list that includes email addresses, and given
that some people have bizarrely long emails, I'd like to limit it to
some value.

Please let me know if this feature is available, or else I'll find out
how to implement it as a filter myself.

Thanks,
Sia

David Pratt

unread,
Feb 26, 2006, 3:48:36 PM2/26/06
to django...@googlegroups.com
Hi Sia. I don't believe you need a filter. Just import textwrap module
and do what you want. See textwrap module on python.org in the docs for
more.

Regards,
David

Siah

unread,
Feb 26, 2006, 4:11:43 PM2/26/06
to Django users
Thanks David. I did feel there should be a way to do this since it
seems common enough.

I'll read up on textwrap now,
Regards,
Sia

Siah

unread,
Feb 26, 2006, 4:16:27 PM2/26/06
to Django users
emm.. But wait a sec! How do I call a python function from django
template. I don't think it is allowed, meaning that I'd still have to
write a filter using textwrap:

>>> wrap('siasookhteh', 5)
['siaso', 'okhte', 'h']

Sia -

Ivan Sagalaev

unread,
Feb 27, 2006, 2:05:01 AM2/27/06
to django...@googlegroups.com
Siah wrote:

>Please let me know if this feature is available, or else I'll find out
>how to implement it as a filter myself.
>
>

A filter would look simple:

def truncate(value,arg):
return value[0:arg]

However it won't work for international characters. This will:

from django.conf.settings import DEFAULT_CHARSET

def truncate(value,arg):
return value.decode(DEFAULT_CHARSET)[0:arg].encode(DEFAULT_CHARSET)

akaihola

unread,
Feb 27, 2006, 2:06:44 AM2/27/06
to Django users
Reading the source code of the "slice" filter in Django it looks to me
like it should work on strings as well as lists. If you only need to
truncate and discard the extra characters, that would be the way to go.

Reply all
Reply to author
Forward
0 new messages