Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django accepting GET parameters

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'),
    )
like image 312
tipu Avatar asked Nov 28 '22 23:11

tipu


1 Answers

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
like image 139
Davor Lucic Avatar answered Dec 06 '22 17:12

Davor Lucic