dkgirl
dkgirl

Reputation: 4739

Django: grabbing parameters

I'm having the hardest time with what should be super simple. I can't grab the passed parameters in django.

In the browser I type:

http://localhost:8000/mysite/getst/?term=hello

My url pattern is:

(r'^mysite/getst/$', 'tube.views.getsearchterms')

My View is

def getsearchterms(request):

my_term = some_way_to_get_term

return HttpResponse(my_term)

In this case it should return "hello". I am calling the view, but a blank value is returned to me. I've tried various forms of GET....

What should some_way_to_get_term be?

Upvotes: 0

Views: 169

Answers (2)

Dominique Guardiola
Dominique Guardiola

Reputation: 3431

By using arbitrary arguments after ? and then catching them with request.GET['term'], you're missing the best features of Django urls module : a consistent URL scheme

If "term" is always present in this URL call it must be meaningful to your application, so your url rule could look like :

(r'^mysite/getst/(?P<term>[a-z-.]+)/', 'tube.views.getsearchterms')

That means :

  1. That you've got a more SEO-FRIENDLY AND stable URL scheme (no ?term=this&q=that inside)
  2. That you can catch your argument easily in your view :

Like this

def getsearchterms(request,term):
    #do wahtever you want with var term
    print term

Upvotes: 0

Bernhard Vallant
Bernhard Vallant

Reputation: 50776

The get parameters can be accesses like any dictionary:

my_term = request.GET['term']
my_term = request.GET.get('term', 'my default term')

Upvotes: 3

Related Questions