Python 在Django中将泛型元素的名称转换为URL
我的目标是从产品名称开始获取产品页面的URL 比如说 从 我想去Python 在Django中将泛型元素的名称转换为URL,python,django,urlencode,Python,Django,Urlencode,我的目标是从产品名称开始获取产品页面的URL 比如说 从 我想去 www.example.com/my-product-2-0/ 从My Product 2.0-->My-Product-2-0 怎么做 尝试使用正则表达式: import re string="My Product 2.0" rs=re.compile(r"\W+") string=re.sub(rs, "-", string) print string 您可能需要使用正则表达式,具体取决于您希望用“-”替换的内容 Dja
www.example.com/my-product-2-0/
从My Product 2.0-->My-Product-2-0
怎么做 尝试使用正则表达式:
import re
string="My Product 2.0"
rs=re.compile(r"\W+")
string=re.sub(rs, "-", string)
print string
您可能需要使用正则表达式,具体取决于您希望用“-”替换的内容 Django有一个slagify函数,正好用于:
from django.template.defaultfilters import slugify
slugify("My Product 2.0") # 'my-product-20'
注意:在当前的开发版本(即将成为1.5版)中,这已经转移到了
django.utils.text
,您是想在模板或视图代码中,还是完全在其他地方这样做?您看了吗?@Talvalin我在视图中。@Sindri还没有。你能给我看一个用例吗?
from django.template.defaultfilters import slugify
slugify("My Product 2.0") # 'my-product-20'