user375348
user375348

Reputation: 789

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!

Upvotes: 5

Views: 9572

Answers (2)

dzida
dzida

Reputation: 8981

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

Upvotes: 4

Mike DeSimone
Mike DeSimone

Reputation: 42825

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

Upvotes: 2

Related Questions