Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match the question mark character in a Django URL?

Tags:

In my Django application, I have a URL I would like to match which looks a little like this:

/mydjangoapp/?parameter1=hello&parameter2=world

The problem here is the '?' character being a reserved regex character.

I have tried a number of ways to match this... This was my first attempt:

(r'^pbanalytics/log/\?parameter1=(?P<parameter1>[\w0-9-]+)&parameter2=(?P<parameter2>[\w0-9-]+), 'mydjangoapp.myFunction')

This was my second attempt:

(r'^pbanalytics/log/\\?parameter1=(?P<parameter1>[\w0-9-]+)&parameter2=(?P<parameter2>[\w0-9-]+), 'mydjangoapp.myFunction')

but still no luck!

Does anyone know how I might match a '?' exactly in a Django URL?

like image 943
Nick Cartwright Avatar asked Mar 31 '11 13:03

Nick Cartwright


People also ask

How will Django match URLs?

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).

What do you call the question mark in a URL?

In a URL, the query starts with a question mark - the question mark is used as a separator, and is not part of the query string. If you also include a question mark in the query string, this would be treated as a literal question mark (i.e. it has no significance beyond that of a regular character).

Can a URL have a question mark?

What Does a Question Mark in URL Do? URLs have query strings that specify parameters through a group of characters typed into a browser to retrieve information. A question mark is not a part of the query string, but it's used to establish boundaries and is considered a separator.


2 Answers

Don't. You shouldn't match query string with URL Dispatcher. You can access all values using request.GET dictionary.

urls

(r'^pbanalytics/log/$', 'mydjangoapp.myFunction')

function

def myFunction(request) 
  param1 = request.GET.get('param1')
like image 125
vartec Avatar answered Oct 04 '22 17:10

vartec


Django's URL patterns only match the path component of a URL. You're trying to match on the querystring as well, this is why you're having trouble. Your first regex does what you wanted, except that you should only ever be matching the path component.

In your view you can access the querystring via request.GET

like image 23
bradley.ayers Avatar answered Oct 04 '22 16:10

bradley.ayers