Craysiii
Craysiii

Reputation: 25

Getting value of URL-encoded request.GET variable in Django Template

I am using Django 1.3 with Python 2.7.2 on Windows 7 x64.

I have a URL pattern like this:

url(r'^(?P<club_id>\d+)/$', 'view_club')

From the pattern I want to be able to use request.GET in my templates to be able to create URLs to my views based on this GET variable (club_id). I have read online that I would be able to do:

{{ request.GET.club_id }}

However, this is always showing up as blank. I cannot figure out the reason why. I have the request context processor in my list of default context processors.

Thanks for the help.

Upvotes: 1

Views: 1894

Answers (2)

Ned Batchelder
Ned Batchelder

Reputation: 376072

In your example, club_id is not a GET parameter, it is part of the path in the URL. Your view function takes club_id as an argument, it should then put it in the context so the template can access it.

For example, your view function:

def view_club(request, club_id):
     return render(request, "template_name.html", { 'club_id': club_id })

then in your template:

{{ club_id }}

Upvotes: 1

Hacking Life
Hacking Life

Reputation: 3373

IF you are passing an variable in the URL - in this case club_id - simply include it as an argument in your view function next to request:

def get_club(request,club_id):
     club = Club.object.get(pk=club_id)
     return render_to_response('club.html', {'club': club})

now in your template you can access {{club}} as the individually selected object and do things like {{club.name}} This also works for variables with multiple objects which you would use a for loop to iterate through.

Upvotes: 0

Related Questions