How to get GET request values in Django Templates?
Asked Answered
L

2

48

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?

Lashawnda answered 25/10, 2010 at 8:20 Comment(0)
R
106

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 }}
Rochkind answered 25/10, 2010 at 8:26 Comment(4)
How to add it in a if condition ?Marlinemarlinespike
Is there a way to add an optional default value in the template? For example, request.GET.get("q", True).Tremann
@Marlinemarlinespike 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 %}.Stinkpot
For later Django versions (maybe > 2.0) this seems to be {{ request.GET.urlencode }}Once
L
3

For example, if you access the url below:

https://example.com/?fruits=apple&meat=beef

Then, you can get the parameters in Django Templates as shown below. *My answer explains it more:

{# "index.html" #}

{{ request.GET.fruits }} {# apple #}
{{ request.GET.meat }} {# beef #}
{{ request.GET.dict }} {# {'fruits': 'apple', 'meat': 'beef'} #}
{{ request.META.QUERY_STRING }} {# fruits=apple&meat=beef #}
Lyall answered 18/9, 2023 at 17:31 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.