【问题标题】:Django values_list returns unicodeDjango values_list 返回 unicode
【发布时间】:2011-07-09 05:19:28
【问题描述】:

我在视图中有以下查询集:

cities = Idea.published.values_list('city', flat=True).distinct()

在我的相应模板中有以下内容:

{% for city in cities %}
    <li><a href="{% url ideas-by-city city %}">{{ city }}</a></li>
{% endfor %}

{{ city }} 变量在渲染页面上打印为字符串,但传递到 url 标记的 city 变量被表示为 unicode:即 u('city')。如何将此变量正确传递到 url 标签中?

谢谢。

【问题讨论】:

  • 你得到 u('city') 了吗?带括号? unicode 应该看起来像 u'city'。检查你的城市模型的 def __unicode__(self) 方法,看看它是否没有返回有趣的东西。
  • 啊。这不是“unicode”表示。这是一个 tuple 的表示,它的内容(像所有 Django 字符串一样)是 unicode 格式的。您的 urlconf 可能有问题。请显示你得到的确切输出。
  • 是的,感谢您的澄清。它是一个内部带有 unicode 表示的元组。如果我像这样 {{ city }} 在模板中打印它,它会显示为例如“Philadelphia”。但是,如果我在 {% url %} 标记中使用它,例如 {% url idea-by-city city %},我会收到此模板错误:Caught NoReverseMatch while rendering: Reverse for 'ideas-by-city' with arguments ' (u'Philadelphia',)' 和关键字参数 '{}' 未找到。
  • 还要澄清一下,“城市”不是模型。它是“创意”模型中的一个字段值。因此,values_list 查询。
  • 又看了一遍,我认为问题出在我的观点上,而不是 url 标签上。

标签: python django unicode


【解决方案1】:

你可能想要

iriencode

{{ value|iriencode }}。请参阅the Django builtins docs 了解更多信息。

【讨论】:

  • 谢谢,但这似乎并没有。仍然出现此错误:Caught NoReverseMatch while rendering: Reverse for 'ideas-by-city' with arguments '(u'Philadelphia',)' and keyword arguments '{}' not found.
猜你喜欢
  • 2012-01-25
  • 2011-09-18
  • 2016-09-05
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 2013-01-31
  • 2014-05-19
  • 1970-01-01
相关资源
最近更新 更多