Jeffrey Steven
Jeffrey Steven

Reputation: 195

Django URL Multiple Paramaters that can contain any character

I want to send multiple parameters through a URL with Django. Typically I could do something like below:

 url(r'^example/(?P<param1>[\w|\W]+)/(?P<param2>[\w|\W]+)/(?P<param3>[\w|\W]+)/$', views.example, name='example')

The problem is that my 3 parameters can include any characters including "/", so if param1 is say a URL itself, then it will mess up the other parameters for if the following paramters are passed:

param1 = "http://cnn.com", param2 = "red", and param3 = "22"

Django will interpret param2 as beginning after the 2nd dash in http://cnn.com. Any idea what the best way to resolve this is?

Thank You!

Upvotes: 0

Views: 68

Answers (1)

Joey Wilhelm
Joey Wilhelm

Reputation: 5819

In a case like this, I would personally use a query string for your parameters. The example given above would use:

/example/?param1=http%3A%2F%2Fcnn.com&param2=red&param3=22

In Python 3, you would do this with:

import urllib.parse

urllib.parse.urlencode({'param1': 'http://cnn.com', 'param2': 'red', 'param3': '22'})

In Python 2, you would do this with:

import urllib

urllib.urlencode({'param1': 'http://cnn.com', 'param2': 'red', 'param3': '22'})

If, on the other hand, you absolutely have to keep them as part of the actual path, you could simply apply url quoting prior to constructing the URL, so your URL would then look like:

/example/http%3A%2F%2Fcnn.com/red/22/

In Python 3, you would do this with:

import urllib.parse

urllib.parse.quote_plus('http://cnn.com')

In Python 2, you would use:

import urllib

urllib.quote_plus('http://cnn.com')

Upvotes: 1

Related Questions