如何在django模板中将unicode更改为string

时间:2014-06-19 17:41:59

标签: python django django-templates django-urls

我收到NoReverseMatch因为我得到的是unicode而不是字符串,有没有办法可以将unicode转换为模板中的字符串?

这是我的常规超链接

# hyperlink in templates
    {% for lst in mylist %}
        <a href="{% url "url_list" lst.user.username %}"> {{ lst.user.username }} </a>
    {% endfor %}

如何在超链接中执行lst.user.username.encode(“utf-8”)?

# hyperlink in templates
    {% for lst in mylist %}
        <a href="{% url "url_list" lst.user.username.encode("utf-8") %}"> {{ lst.user.username }} </a>
    {% endfor %}



# Url
    url(r'^(?P<username>[-\w]+)/list/$', url_list.as_view(), name='url_list'),

编辑:

我在我的网址中更改了正则表达式,现在正在使用。

url(r'^(?P<username>[\w.@+-]+)/list/$', url_list.as_view(), name='url_list'),

1 个答案:

答案 0 :(得分:1)

django会自动将unicode字符串渲染为utf-8。

也许问题是网址路由?尝试在正则表达式模式之前添加ur

url(ur'^(?P<username>[-\w]+)/list/$', url_list.as_view(), name='url_list'),