开发者

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

开发者 https://www.devze.com 2023-02-20 20:22 出处:网络
In my Django application, I have a URL I would like to match which looks a little like this: /mydjangoapp/?parameter1=hello&parameter2=world

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?


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


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


The ? character is a reserved symbol in regex, yes. Your first attempt looks like proper escaping of it.

However, ? in a URL is also the end of the path and the beginning of the query part (like this: protocol://host/path/?query#hash. Django's URL dispatcher doesn't let you dispatch URLs based on the query part, AFAIK.

My suggestion would be writing a django view that does the dispatching based on the request.GET parameter to your view function.


The way to do what the original question was i.e. catch-all in URL dispatch var...

url(r'^mens/(?P<pl_slug>.+)/$', 'main.views.mens',),

or

url(r'^mens/(?P<pl_slug>\?+)/$', 'main.views.mens',),

As far as why this is needed, GET URL's don't exactly provide good "permalinks" or good presentation in general for customers and to clients.

Clients often times request the url be formatted i.e.

www.example-clothing-site.com/mens/tops/shirts/t-shirts/Big_Brown_Shirt3XL

this is a far more readable interface for the end-user and provides a better overall presentation for the client.

0

精彩评论

暂无评论...
验证码 换一张
取 消