In Django I want to use a simple template tag to truncate data.
在Django中,我想使用一个简单的模板标记来截断数据。
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)
'ascii' codec不能编码字符u'\u2013'在位置84:序数不在范围(128)
Error is on line starting data = str(value)
在开始数据= str(值)时出错
Why?
为什么?
3 个解决方案
#1
10
try to use unicode() to convert value (instead of str()):
尝试使用unicode()来转换值(而不是str()):
data = unicode(value)
#2
26
If you're using django and python 2.7 this fixes it for me:
如果你使用的是django和python 2.7,那么这就为我修复了:
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
看到https://docs.djangoproject.com/en/dev/ref/utils/ django.utils.encoding.python_2_unicode_compatible
#3
5
@max4ever 's answer works for me. also sometimes you should put this line in the head of python files:
@max4ever的回答对我很管用。有时你也应该在python文件的开头写上这句话:
from __future__ import unicode_literals
it can be helpful when solving unicode encoding issues like this one.
它可以帮助解决像这样的unicode编码问题。
#1
10
try to use unicode() to convert value (instead of str()):
尝试使用unicode()来转换值(而不是str()):
data = unicode(value)
#2
26
If you're using django and python 2.7 this fixes it for me:
如果你使用的是django和python 2.7,那么这就为我修复了:
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
看到https://docs.djangoproject.com/en/dev/ref/utils/ django.utils.encoding.python_2_unicode_compatible
#3
5
@max4ever 's answer works for me. also sometimes you should put this line in the head of python files:
@max4ever的回答对我很管用。有时你也应该在python文件的开头写上这句话:
from __future__ import unicode_literals
it can be helpful when solving unicode encoding issues like this one.
它可以帮助解决像这样的unicode编码问题。