2012-07-14 30 views
0

我有一个自定义模板标签来替换空格,制表符,换行符,!,@,#,$,%,&,(,),。,与前围:正则表达式只适用于显式给定unicode字符串不在模型的unicode字段

re.sub('[,@#$%&_.?!\t\n ]+', '-', value) 

这工作得很好,当我给value parameter explicitly

re.sub('[,@#$%&_.?!\t\n ]+', '-', 'نمونه کد') 

或:

value='نمونه کد' 
re.sub('[,@#$%&_.?!\t\n ]+', '-', value) 

但在TEM片时我想使用这个标签上的对象列表的subject场不correctely工作,只是替换空间与前围:

{% for n in news %} 
    <a href="{% url CompanyHub.views.getNews n.subject|custom_unicode_slugify,n.pk %}" >{{n.description|safe|truncatewords_html:15}}</a> 
{% endfor %} 

这是我custome模板标签:

def custom_unicode_slugify(value): 
    return re.sub('[,@#$%&_.?!\t\n ]+', '-', value) 

register.filter('custom_unicode_slugify', custom_unicode_slugify) 

我tryed使用这个标签没有n|custom_unicode_slugify代替n.subject|custom_unicode_slugify,因为我的模型__unicode__()方法返回subject field,但我得到这个错误:

Caught TypeError while rendering: expected string or buffer 

回答

0

我终于想出了这个解决方案:使用 模板标签unicode method不会立即执行的时候,所以我在models.py definded unicode subject除了__unicode__

def __unicode__(self): 
    return self.subject 
def unicode_subject(self): 
    return unicode(self.subject) 

模板:

<a href="{% url CompanyHub.views.DocDetails doc.unicode_subject|custom_unicode_slugify,doc.pk %}">{{doc.content}}</a> 
相关问题