views:

21

answers:

2

Hello, 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!

A: 

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

Lukasz Dziedzia
BTW, `\w` includes `_`, and `-` is treated as a character rather than a range marker if it's the first thing after the `[` (and optional `^`), so you could write `(?P<string>[-\w]+)`.
Mike DeSimone
+1  A: 

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 +).

Mike DeSimone