【问题标题】:how to change unicode to string in django template如何在 django 模板中将 unicode 更改为字符串
【发布时间】:2014-06-19 17:41:59
【问题描述】:

我得到 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'),

【问题讨论】:

  • Unicode 绝对不是这里的问题。您应该发布确切的错误消息和回溯。

标签: python django django-templates django-urls


【解决方案1】:

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

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

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

【讨论】:

  • 添加你没有用,但你的帖子确实帮助我检查了我的网址。谢谢,我给你加分。
猜你喜欢
  • 1970-01-01
  • 2017-05-22
  • 2016-02-25
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
相关资源
最近更新 更多