Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Django中将泛型元素的名称转换为URL_Python_Django_Urlencode - Fatal编程技术网

Python 在Django中将泛型元素的名称转换为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

我的目标是从产品名称开始获取产品页面的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

您可能需要使用正则表达式,具体取决于您希望用“-”替换的内容

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'