Python Django GET Requests

I’ve worked extensively with Django, one of the most powerful web frameworks out there. One of the fundamental tasks you’ll encounter while building web applications is handling GET requests.

In this tutorial, I’ll walk you through everything you need to know about handling GET requests in Django, including practical code examples tailored to real-world scenarios.

Let’s get in!

What is a GET Request in Django?

GET requests are the most common HTTP requests used to retrieve data from a server. When a user visits a webpage or submits a form without changing data, the browser sends a GET request. In Django, handling these requests involves working with views, URLs, and request objects.

Check out Python Django Search With Dropdown Filter

How to Access GET Data in Django Views

Django provides a straightforward way to access GET parameters through the request.GET dictionary-like object. This allows you to read query parameters sent via the URL.

Example 1: Basic GET Request Handling

Imagine you’re building a simple app to search for employees by their department in a company based in New York.

Here’s a complete example:

# views.py
from django.http import HttpResponse
from django.shortcuts import render

# Sample data representing employees
EMPLOYEES = [
    {'name': 'John Doe', 'department': 'Finance'},
    {'name': 'Jane Smith', 'department': 'Marketing'},
    {'name': 'Alice Johnson', 'department': 'Finance'},
    {'name': 'Bob Brown', 'department': 'IT'},
]

def employee_search(request):
    # Access the 'department' query parameter from the URL
    department = request.GET.get('department', '').capitalize()

    # Filter employees based on the department parameter
    if department:
        filtered_employees = [emp for emp in EMPLOYEES if emp['department'] == department]
    else:
        filtered_employees = EMPLOYEES

    # Pass filtered data to the template
    context = {'employees': filtered_employees, 'department': department}
    return render(request, 'employee_search.html', context)
<!-- employee_search.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Employee Search</title>
</head>
<body>
    <h1>Employee Search</h1>
    <form method="get">
        <label for="department">Department:</label>
        <input type="text" id="department" name="department" value="{{ department }}">
        <button type="submit">Search</button>
    </form>

    <h2>Results:</h2>
    <ul>
        {% for employee in employees %}
            <li>{{ employee.name }} - {{ employee.department }}</li>
        {% empty %}
            <li>No employees found in this department.</li>
        {% endfor %}
    </ul>
</body>
</html>

URL Configuration

# urls.py
from django.urls import path
from .views import employee_search

urlpatterns = [
    path('employees/', employee_search, name='employee_search'),
]

I executed the above example code and added the screenshot below.

django get

How this works:
When a user visits /employees/?department=finance, the view reads the department parameter from the URL, filters the employee list accordingly, and renders the results.

Read Run Python Function by Clicking on HTML Button in Django

Method 2: Use Class-Based Views (CBVs) to Handle GET Requests

If you prefer a more structured approach, Django’s class-based views provide a clean way to handle GET requests.

Here’s how you can rewrite the above example using a CBV:

# views.py
from django.views import View
from django.shortcuts import render

class EmployeeSearchView(View):
    def get(self, request):
        department = request.GET.get('department', '').capitalize()
        if department:
            filtered_employees = [emp for emp in EMPLOYEES if emp['department'] == department]
        else:
            filtered_employees = EMPLOYEES

        context = {'employees': filtered_employees, 'department': department}
        return render(request, 'employee_search.html', context)

Update your URL pattern accordingly:

# urls.py
from django.urls import path
from .views import EmployeeSearchView

urlpatterns = [
    path('employees/', EmployeeSearchView.as_view(), name='employee_search'),
]

I executed the above example code and added the screenshot below.

get Django

This method is especially useful when your view needs to handle multiple HTTP methods or requires more complex logic.

Check out Add a Dropdown Navbar in Django

Handle Multiple Query Parameters

Often, you’ll want to handle more than one parameter in a GET request. For example, filtering employees by both department and city.

Example: Filter by Department and City

def employee_search(request):
    department = request.GET.get('department', '').capitalize()
    city = request.GET.get('city', '').capitalize()

    filtered_employees = EMPLOYEES

    if department:
        filtered_employees = [emp for emp in filtered_employees if emp['department'] == department]

    if city:
        # Assuming each employee dictionary has a 'city' key
        filtered_employees = [emp for emp in filtered_employees if emp.get('city', '').capitalize() == city]

    context = {'employees': filtered_employees, 'department': department, 'city': city}
    return render(request, 'employee_search.html', context)

Update your template form to include the city input:

<label for="city">City:</label>
<input type="text" id="city" name="city" value="{{ city }}">

Best Practices When Working with GET Requests in Django

  • Validate Input: Always sanitize and validate GET parameters to prevent security risks like injection attacks.
  • Use Default Values: Use .get() with default values to avoid errors if parameters are missing.
  • Keep URLs Clean: Avoid sending sensitive data via GET parameters.
  • Paginate Results: For large datasets, consider paginating the results to improve performance and user experience.
  • Leverage Django Forms: For complex query parameters, consider using Django forms to handle validation and rendering.

Read Create a Function-Based View in Django

Debug GET Requests

If you want to quickly check what GET parameters your view is receiving, you can print or log request.GET:

def employee_search(request):
    print(request.GET)  # For debugging purposes
    # rest of your code

I hope this guide helps you understand how to work with GET requests in Django effectively. Whether you’re building a simple search feature or a more complex filtering system, these methods will serve you well.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.