5

I want to route the following uri to a view;

localhost:8000/?tag=Python

to

def index_tag_query(request, tag=None):

in my url conf, I've tried the following regex patterns but none seem to be capturing the request even though the regex looks good;

url(r'^\?tag=(?P<tag>\w+)/$', 'links.views.index_tag_query'),

url(r'^\/?\?tag=(?P<tag>\w+)/$', 'links.views.index_tag_query'),

url(r'^\/?\?tag=(?P<tag>.*)/$', 'links.views.index_tag_query'),

What gives?

Kevin
  • 1,113
  • 3
  • 12
  • 26

1 Answers1

8

You can't parse GET parameters from your URLconf. For a better explanation then I can give, check out this question (2nd answer): Capturing url parameters in request.GET

Basically, the urlconf parses and routes the URL to a view, passing any GET parameters to the view. You deal with these GET parameters in the view itself

urls.py

url(r^somepath/$', 'links.views.index_tag_query')

views.py

def index_tag_query(request):
    tag = request.GET.get('tag', None)
    if tag == "Python":
         ...
Community
  • 1
  • 1
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
  • Cool. I tried that approach originally but felt there was a better way to achieve it in the URL conf. I have now changed the URI to be `url(r'^tag/(?P.*)/$', 'links.views.index_tag_query', name='tag-search')` which works great and removes the need for extra conditionals inside a view function. – Kevin Jan 29 '12 at 11:57
  • Yea, that's the best way of doing it. I think it's a good idea to use your URLs to construct the queryset (i.e. what data to grab), and GET parameters to adjust it (how to return it - sorting, exlclusions etc) – Timmy O'Mahony Jan 29 '12 at 12:07