47

Is it correct to say that there is no simple tag that just writes some http get query parameter? If all needed is printing a http get query parameter e.g. ?q=w can I directly use the value q with a template tag or need the copy the value in the request handler? Is it possible to more directly pass values (all values) from http get to template? Because copying every value seems repeating the same handling many times

template_values = {'q':self.request.get('q'),...

It should be possible to iterate the parameter set. Can you recommend that or any other solution?

Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424

1 Answers1

105

You don't need to do this at all. The request is available in the template context automatically (as long as you enable the request context processor and use a RequestContext) - or you can just pass the request object directly in the context.

And request.GET is a dictionary-like object, so once you have the request you can get the GET values directly in the template:

{{ request.GET.q }}
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 1
    How to add it in a if condition ? – Root Dec 25 '17 at 20:45
  • Is there a way to add an optional default value in the template? For example, request.GET.get("q", True). – Mike Stoddart Jan 15 '18 at 20:08
  • 1
    @Root Use `{% if 'q' in request.GET %}` before retrieving the value. If you wanted to use a default value if `q` is not present, you can tag on an `{% else %}`. – alstr Nov 09 '18 at 10:09
  • 7
    For later Django versions (maybe > 2.0) this seems to be `{{ request.GET.urlencode }}` – Markus Nov 23 '18 at 11:22