GET Query Parameters

GET Query Parameters

Query parameters are commonly used to pass optional data through the URL.
In Django, these parameters can be accessed using request.GET.

 

Example of a query parameter URL:
jaimedcsilva.com/?param=value1

Example of a URL parameter:
jaimedcsilva.com/value1/

 

Template example

...
<a href="/?param=value1">Value 1</a> 
<a href="/?param=value2">Value 2</a>

 

Retrieving the parameter in the backend

from django.views.generic import TemplateView

class index(TemplateView):
    template_name = 'polls/index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        param = self.request.GET.get('param')

        print(param)

        context['param'] = param
        context['message'] = "Some message from the server!"

        return context

 

If the param is missing, request.GET.get() returns None. You can also provide a default value: 

param = self.request.GET.get("param", "default")

Tested with Django 4.2