0

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!

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

would this still work if the url you were parsing included its own query string such as a link like this: nytimes.com/2015/09/06/opinion/sunday/…
Yup! >>> urllib.parse.quote_plus('http://www.nytimes.com/2015/09/06/opinion/sunday/adam-grant-friends-at-work-not-so-much.html?smid=tw-share&_r=1') 'http%3A%2F%2Fwww.nytimes.com%2F2015%2F09%2F06%2Fopinion%2Fsunday%2Fadam-grant-friends-at-work-not-so-much.html%3Fsmid%3Dtw-share%26_r%3D1'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.