Detect if the URL query parameter exists in Django

We can send and retrieve value via URL as the GET method. By default, the HTML form data submitted via URL query or parameters. Sending values via URL is known as the GET method.

In Django, it is easy to retrieve the value from URL query. We can don it in both views file and a template file.


Detect if the URL parameter exists in Django view

Suppose, we have “product_id” in URL query and we want to get that value. In that case, we can get the “product_id” URL parameter value in our Django view just like you can see below:

def product(request):
    product_id = request.GET['product_id']

But, if the URL parameter doesn’t exist, then we will get an error from Django.

Of course, we don’t want to show these types of error in our project. So we have to detect if the GET value in URL exists in Django.

It is quite simple to check if the URL parameter exists or not in Django. Below is the Python code in Django view that will do that task:

if request.method == 'GET' and 'product_id' in request.GET:
   product_id = request.GET['product_id']
   product_id = 0

For class-based views

The above code is for a function based views. For class-based views in Django, below is the Python code to check if the URL parameter exists:

def get_context_data(self, **kwargs):
      context = super().get_context_data(**kwargs)
      if self.request.method == 'GET' and 'product_id' in self.request.GET:
           context['product_id'] = self.request.GET['product_id']
           context['product_id'] = ""

It is very similar to function based views, the main difference is that we have used the self key here.


Also, read:


Detect if GET value exists in the Django template file

We can also detect if the GET value exists or not in the template file too.

Below is the code to detect if it exists in our template file:

{% if 'product_id' in request.GET %}
    Product ID exists
{% endif %}


So, we have learned how to check if the URL parameter value exists or not in Django. You have seen both the code for views and template file for this task. But in most of the cases, it is done in views.

Leave a Reply

Your email address will not be published. Required fields are marked *