Handling HTTP Requests and Responses in Django

In Django, a view is a Python function responsible for processing an incoming web request and returning a response. These views are typically defined in the views.py file within an application directory. The response can be an HTML page, a redirect, a 404 error, or any other HTTP content type.

URL Configuration (URLconf)

To direct a specific URL to a view, Django uses the URLconf module. The ROOT_URLCONF setting in the project's settings.py file points to the root URL configuration. The workflow involves defining a list called urlpatterns which contains mappings between URL patterns and view functions.

It is best practice to separate URL configurations. The main project urls.py usually includes the URL configurations from individual applications.

# project/urls.py
from django.urls import include, re_path

urlpatterns = [
    re_path(r'^library/', include('library.urls')),
]

Inside the application, specific patterns are defined.

# library/urls.py
from django.urls import re_path
from . import views

urlpatterns = [
    re_path(r'^$', views.home),
    re_path(r'^(?P<book_id>\d+)/$', views.book_detail),
]

Regular expressions are used for matching. The URL string matched does not include the domain or GET parameters. When defining patterns, it is recommended to omit the leading slash and include a trailing slash (e.g., r'^items/$').

Capturing Parameters

Parameters can be extracted from URLs using regex groups.

  • Positional Arguments: Use simple parentheses. The captured value is passed as a positional argument to the view.
    # URL pattern
    re_path(r'^(\d+)/$', views.show_item)
    
    # View
    from django.http import HttpResponse
    
    def show_item(request, item_id):
        return HttpResponse(f'Item ID: {item_id}')
    
  • Named Arguments: Use the ?P<name> syntax. The captured value is passed as a keyword argument.
    # URL pattern
    re_path(r'^(?P<slug>\w+)/$', views.show_slug)
    
    # View
    def show_slug(request, slug):
        return HttpResponse(f'Slug: {slug}')
    

Built-in Error Views

Django includes default views for HTTP errors. To see these custom error pages, DEBUG must be set to False in settings, and ALLOWED_HOSTS must be configured.

  • 404 (Page Not Found): Triggered when no URL pattern matches. It renders 404.html.
  • 500 (Server Error): Triggered by exceptions in view code. It renders 500.html.
  • 400 (Bad Request): Triggered by suspicious activity, like a corrupted cookie. It renders 400.html.

The HttpRequest Object

When a request is made, Django creates an HttpRequest object containing metadata. This object is passed as the first argument to the view.

Key Attributes

  • path: The full path of the request (excluding the domain).
  • method: The HTTP method string (e.g., 'GET', 'POST').
  • encoding: The encoding used to decode form data.
  • GET: A dictionary-like object containing GET parameters.
  • POST: A dictionary-like object containing POST form data.
  • FILES: A dictionary-like object containing uploaded files.
  • COOKIES: A dictionary containing cookie data.
  • session: A dictionary-like object for session data.

QueryDict Objects

Both request.GET and request.POST are QueryDict objects. Unlike standard Python dictionaries, they can handle multiple values for the same key.

  • get(key): Returns the last value for the specified key.
  • getlist(key): Returns a list of all values for the specified key.
# Example: Handling GET parameters
def search_view(request):
    query = request.GET.get('q', '')
    filters = request.GET.getlist('filter')
    return HttpResponse(f'Query: {query}, Filters: {filters}')

The HttpResponse Object

Views must return an HttpResponse object.

Attributes and Methods

  • content: The body of the response.
  • status_code: The HTTP status (default 200).
  • set_cookie(key, value, max_age=None): Sets a cookie on the client.
from django.http import HttpResponse

def simple_view(request):
    resp = HttpResponse("Content Loaded", content_type='text/plain')
    resp.set_cookie('user_token', 'abc123', max_age=3600)
    return resp

Rendering Templates

The render() shortcut combines a template with a context dictionary and returns an HttpResponse.

from django.shortcuts import render

def profile_view(request):
    context = {'username': 'jdoe', 'level': 5}
    return render(request, 'profile.html', context)

JsonResponse

For AJAX requests, JsonResponse simplifies returning JSON data.

from django.http import JsonResponse

def api_data(request):
    data = {'status': 'success', 'id': 1042}
    return JsonResponse(data)

Redirection

To redirect users, use the redirect() shortcut.

from django.shortcuts import redirect

def login_success(request):
    return redirect('/dashboard/')

State Management

Cookies

Cookies store small pieces of data on the client's browser. They are sent with every request to the server.

  • Setting: Use response.set_cookie().
  • Reading: Use request.COOKIES.get().
def read_cookie(request):
    val = request.COOKIES.get('settings')
    return HttpResponse(f'Settings: {val}')

Sessions

Sessions store data on the server side, linked to a user via a session ID cookie. This is more secure than storing sensitive data directly in cookies.

Session storage can be configured in settings.py via SESSION_ENGINE. Options include database storage (default), cached storage, or file-based storage.

# Using Redis for Sessions (settings.py)
SESSION_ENGINE = 'redis_sessions.session'
SESSION_REDIS_HOST = 'localhost'
SESSION_REDIS_PORT = 6379
SESSION_REDIS_DB = 0
SESSION_REDIS_PREFIX = 'session'

Session data is accessed like a dictionary.

# Writing to session
def save_preferences(request):
    request.session['theme'] = 'dark'
    return HttpResponse('Saved')

# Reading from session
def load_preferences(request):
    theme = request.session.get('theme', 'light')
    return HttpResponse(f'Current theme: {theme}')

Sessions can be cleared using request.session.flush() or by deleting specific keys with del request.session['key'].

Tags: Django python web development Backend

Posted on Sat, 09 May 2026 23:36:55 +0000 by thefarhan