得到django slugify的错误

fds*_*gds 5 python django slug

我正在尝试这个

from django.utils.text import slugify

In [8]: mystr = "This is john"

In [9]: slugify(mystr)
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误

TypeError: must be unicode, not str

如果我使用这个

from django.template.defaultfilters import slugify那么它的工作原理,但它不chnage underscoreshyphens,如果我有dots它简单的删除它

Hen*_*son 5

这是因为slugify()需要一个unicode对象.

解决它的最简单方法是将字符串作为unicode对象传递

mystr = u'This is John'
Run Code Online (Sandbox Code Playgroud)

要么

mystr = unicode('This is John')
>> u'This is John'
Run Code Online (Sandbox Code Playgroud)

  • 对于未来的搜索者......这个答案仅与Python 2相关.Python 3中没有unicode(),Python 3中的所有字符串都是Unicode. (2认同)