【发布时间】:2021-12-14 07:09:00
【问题描述】:
我的模型 Author 带有字段 firstname, lastname。我想添加另一个字段 'slug' 这将包含一个字段串联的块。但是,这些字段包含非英文字符,我需要一个英文 slug 来创建链接模板 "localhost/authors/str::slug" 如何实现?
【问题讨论】:
我的模型 Author 带有字段 firstname, lastname。我想添加另一个字段 'slug' 这将包含一个字段串联的块。但是,这些字段包含非英文字符,我需要一个英文 slug 来创建链接模板 "localhost/authors/str::slug" 如何实现?
【问题讨论】:
要解决此问题,您可以使用unidecode 和slugify。
你应该通过pip install unidecode安装它
from unidecode import unidecode
from django.template import defaultfilters
slug = defaultfilters.slugify(unidecode(input_text))
示例:
import unidecode
a = unidecode.unidecode('привет')
the answer will be ('privet') #this is just an example in russian.
and after that you can apply slugify
【讨论】:
unidecode后申请slugify
您可以先使用trans 将名称转换为拉丁字符。
pip install trans
from trans import trans
from django.utils.text import slugify
author_slug = slugify( trans(first_name + " " + last_name) )
或者如果你不介意这样的字符:%20, %C3,你可以使用
from urllib.parse import quote
author_slug = slugify( quote(first_name + " " + last_name) )
【讨论】: