[英]Django url pattern - parameter with forward slash
How can I create a url pattern for two parameters where the first parameter contains a forward slash as part of its contents: 如何为两个参数创建url模式,其中第一个参数包含正斜杠作为其内容的一部分:
da/ta1=/data2
Intially I had the following pattern: 最初,我有以下模式:
(r'^view/(?P<item_id>\w+=)/(?P<changekey>\w+)/$', 'view'),
However this pattern does not match because of the first forward slash which is part of the parameter data. 但是,由于第一个正斜杠是参数数据的一部分,因此该模式不匹配。
Assuming you construct the url yourself, you could use quote_plus
to encode the inline forward slash: 假设您自己构造了url,可以使用
quote_plus
来编码内联正斜杠:
>>> '/'.join([urllib.quote_plus(d) for d in ['da/ta1', 'data2']])
'da%2Fta1/data2'
And to decode: 并解码:
>>> urllib.unquote_plus('da%2Fta1/data2')
'da/ta1/data2'
To then match your data, your pattern could be changed to the construct found below. 然后,为了匹配您的数据,您的模式可以更改为下面的构造。 For the first parameter, this matches everything up to the
=
character; 对于第一个参数,这匹配到
=
字符的所有内容; the second parameter is expected to be alphanumerical. 第二个参数预计是字母数字。
(r'^view/(?P<item_id>[^=]+)=/(?P<changekey>\w+)/$', 'view')
Django Admin does have the same problem with slashes in parameters. Django Admin在参数斜杠方面确实存在同样的问题。 To fix this, Django uses its own quote function:
为了解决这个问题,Django使用自己的引用函数:
from django.contrib.admin.utils import quote
quote(param1)
In the view itself: 在视图中:
unquote(self.kwargs.get('param1'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.