Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django url parsing -pass raw string

I'm trying to pass a 'string' argument to a view with a url. The urls.py goes

('^add/(?P<string>\w+)', add ),

I'm having problems with strings including punctuation, newlines, spaces and so on. I think I have to change the \w+ into something else. Basically the string will be something copied by the user from a text of his choice, and I don't want to change it. I want to accept any character and special character so that the view acts exactly on what the user has copied.

How can I change it?

Thanks!

like image 566
user375348 Avatar asked Jun 25 '10 11:06

user375348


2 Answers

Notice that you can use only strings that can be understood as a proper URLs, it is not good idea to pass any string as url.

I use this regex to allow strings values in my urls:

(?P<string>[\w\-]+)

This allows to have 'slugs; in your url (like: 'this-is-my_slug')

like image 53
dzida Avatar answered Sep 25 '22 15:09

dzida


Well, first off, there are a lot of characters that aren't allowed in URLs. Think ? and spaces for starters. Django will probably prevent these from being passed to your view no matter what you do.

Second, you want to read up on the re module. It is what sets the syntax for those URL matches. \w means any upper or lowercase letter, digit, or _ (basically, identifier characters, except it doesn't disallow a leading digit).

The right way to pass a string to a URL is as a form parameter (i.e. after a ?paramName= in the URL, and with special characters escaped, such as spaces changed to +).

like image 35
Mike DeSimone Avatar answered Sep 25 '22 15:09

Mike DeSimone