views:

64

answers:

1

Error can be seen here: http://djaffry.selfip.com:8080/

I want the index page to accept parameters, whether it be

mysite.com/search/param_here

or

mysite.com/?search=param_here

I have this in my URL patterns, but I can't get it to work. Any suggestions?

urlpatterns = patterns('',
        (r'^$/(?P<tag>\w+)', 'twingle.search.views.index'),
    )
+5  A: 

First of all your regular expression in url pattern is wrong.

r'^$/(?P<tag>\w+)'

It says to match everything from

  • ^ the beginning of line
  • $ to the end of line
  • having pattern named tag which is composed of words and digits after the line end

Usually after the one line ends comes another line or EOF not content (unless you use multiline regexp and you don't need those here).

Line end should be after the tag:

r'^/(?P<tag>\w+)$'

Using a query string

Query strings are not parsed by url reslover.

Thus, if you have url in format:

http://mysite.com/?query=param_here

will match:

(r'^$', 'twingle.search.views.index')

In this case you can access query string in view like so:

request.GET.get('query', '')

Without a query string

mysite.com/search/param_here 

will match:

(r'^search/(?P<query>\w+)$', 'twingle.search.views.index'),

Where everything that matches \w (you should change this to suite your needs) will be passed along with request to index view function as argument named query.

Both

You can use both url patterns like so:

urlpatterns = patterns('twingle.search.views',
   url(r'^$', 'index'),
   url(r'^search/(?P<query>\w+)$', 'index'),
)

In this example the view would look something like this:

def index(request, query=None)
    if not query:
       query = request.GET.get('query', '')
    # do stuff with `query` string
rebus
I am getting an error using `url(r'^search/(?P<param>\w+)$', 'index')`, invalid syntax (urls.py, line 9)any idea why?
tipu
If you copy/pasted my last urlpatterns example code with both patterns, it seems i forgot a comma after the first url pattern. I've fixed ti now.
rebus
I've also edited urlpatterns (renamed `<param>` to `<query>`) to be easier to use in view and added a view example.
rebus