使用特殊字符反转Django URL

时间:2022-10-17 19:56:16

I'm required to have part number that is defined to any character in addition to widespace, forward slash(/) and dash(-). Furthermore I want to have urls like /part//

除了宽空,正斜杠(/)和短划线( - )之外,我还需要为任何字符定义部件号。此外我想要/ ur // url //

I'm trying to get both urls.py to work in addition to reverse url lookup in my templates.

我试图让urls.py除了我的模板中的反向URL查找之外还能工作。

In urls.py I have defined

在urls.py我定义了

url(r'^part/(?P<part_number>[A-Z0-9- ]{3,20})', 'inventory.views.part'),

and in my templates I'm using

在我正在使用的模板中

{% url inventory.views.part part.part_number %}"

But this causes "Caught NoReverseMatch while rendering" exception, with both par numbers with slash and space.

但这会导致“渲染时捕获NoReverseMatch”异常,并且par值都带有斜杠和空格。

I've seen in the admin interface that the space part numbers are shown correctly (just with space) and the part numbers with slash are shown with "_2F" encoding in the url. Example, part number "1A17OE / JHA7660" is encoded as "/part/1A17OE _2F JHA7660/" in the admin interface.

我在管理界面中看到空格部件编号正确显示(只是空格),带斜杠的部件编号在网址中以“_2F”编码显示。示例,部件号“1A17OE / JHA7660”在管理界面中编码为“/ part / 1A17OE _2F JHA7660 /”。

How is does the admin url accomplish this, and how can I do the same thing?

管理员网址如何实现这一目标,我该如何做同样的事情?

Thanks in advance, Raggi

感谢提前,拉吉

1 个解决方案

#1


1  

You should use urlencode to encode whitespaces in the part number.

您应该使用urlencode来编码部件号中的空白。

#1


1  

You should use urlencode to encode whitespaces in the part number.

您应该使用urlencode来编码部件号中的空白。