Imran Azad
Imran Azad

Reputation: 1404

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:

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.

Upvotes: 1

Views: 4710

Answers (2)

tzanke
tzanke

Reputation: 338

Django Admin does have the same problem with slashes in parameters. To fix this, Django uses its own quote function:

from django.contrib.admin.utils import quote
quote(param1)

In the view itself:

unquote(self.kwargs.get('param1'))

Upvotes: 1

jro
jro

Reputation: 9474

Assuming you construct the url yourself, you could use quote_plus to encode the inline forward slash:

>>> '/'.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')

Upvotes: 2

Related Questions