17

In Django I want to use a simple template tag to truncate data.

This is what I have so far:

@register.filter(name='truncate_simple')
def truncate_char_to_space(value, arg):
    """
    Truncates a string after a given length.
    """
    data = str(value)
    if len(value) < arg:
        return data

    if data.find(' ', arg, arg+5) == -1:
        return data[:arg] + '...'
    else:
        return data[:arg] + data[arg:data.find(' ', arg)] + '...'

But when I use it I get the following error:

{{ item.content|truncate_simple:5  }}

Error:

'ascii' codec can't encode character u'\u2013' in position 84: ordinal not in range(128)

Error is on line starting data = str(value)

Why?

GrantU
  • 6,325
  • 16
  • 59
  • 89

4 Answers4

29

If you're using django and python 2.7 this fixes it for me:

from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Utente(models.Model):

see https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.encoding.python_2_unicode_compatible

tony19
  • 125,647
  • 18
  • 229
  • 307
max4ever
  • 11,909
  • 13
  • 77
  • 115
12

try to use unicode() to convert value (instead of str()):

data = unicode(value)
arturex
  • 568
  • 5
  • 11
  • perfect, but could you explain. – GrantU Jul 31 '13 at 16:20
  • 12
    Please don't randomly suggest adding a coding declaration. The question has nothing to do with that - it is for defining the encoding of character literals in the source file. – Daniel Roseman Aug 01 '13 at 08:06
  • 2
    @DanielRoseman is right about coding declaration. To decoding character unicode(value) is sufficient. – arturex Aug 01 '13 at 09:51
6

@max4ever 's answer works for me. also sometimes you should put this line in the head of python files:

from __future__ import unicode_literals

it can be helpful when solving unicode encoding issues like this one.

realhu
  • 935
  • 9
  • 12
4

in settings.py add this

import sys
reload(sys)
sys.setdefaultencoding('UTF8')
Community
  • 1
  • 1