Delicinq
Delicinq

Reputation: 21

Problem trying to pass url as a parameter to a django view

In my django view I have something like this:

def addOtherItemsForUserAndEvent(request, eventId, itemName, itemLink):

This matches up with my urls.py where I have this:

(r'^addOtherItemsForUserAndEvent/(?P<eventId>\d+)/(?P<itemName>\w{0,100})/(?P<itemLink>\w{0,500})/$', 'gatherings.views.addOtherItemsForUserAndEvent'),

The purpose of this is to create an item with the name and item url and then adds that item to an event. I'm trying to use this via an ajax call and it kind of works, but is very easily broken.

My problem pops up when I try to pass an actual url as the item link like this:

http://127.0.0.1:8000/addOtherItemsForUserAndEvent/1/Pony/http://www.google.ca//

The above example should create an item named pony with a link to google, but it doesn't match up with my url because of the extra "/'s". It seems like I either need to modify my url regex somehow, or else somehow encode the url or pass it differently....

Any help would be greatly appreciated!

Upvotes: 2

Views: 2121

Answers (2)

Dominique Guardiola
Dominique Guardiola

Reputation: 3431

To solve the extra slashes problem, you should url-encode your itemLink parameter (that is, before passing it, in the asolute url definition of this item)

You can use the python urllib library to do this :

import urllib
#when defining the absolute url in get_absolute_url() for example
urllib.quote('http://www.google.ca/?q=django', safe='')
# which will output
>> 'http%3A%2F%2Fwww.google.ca%2F%3Fq%3Ddjango'

The empty safe parameter is needed, or urllib will not encode the "/" Then to decode this in your view, you juste use :

urllib.unquote(itemLink)

Upvotes: 4

girasquid
girasquid

Reputation: 15516

You probably want to change your URL regex to .{0,500} in the last part - \w isn't going to match the punctuation in your URL.

Upvotes: 0

Related Questions