0
0
Djangoframework~5 mins

HttpRequest object in Django

Choose your learning style9 modes available
Introduction

The HttpRequest object holds all the information about a web request from a user. It helps your Django app understand what the user wants.

When you want to get data sent by a user through a form.
When you need to check which page or URL the user requested.
When you want to read cookies or session data from the user.
When you want to know the method used (GET, POST) in the request.
When you want to access headers or user information from the request.
Syntax
Django
def view_function(request):
    # request is an HttpRequest object
    pass
The HttpRequest object is automatically passed to your view functions by Django.
You can access many details like request.method, request.GET, request.POST, request.COOKIES, and more.
Examples
This example reads the user's browser info from the request headers.
Django
from django.http import HttpResponse

def my_view(request):
    user_agent = request.META.get('HTTP_USER_AGENT', '')
    return HttpResponse(f"Your browser is {user_agent}")
This example checks if the request is a POST and reads form data.
Django
from django.http import HttpResponse

def submit_form(request):
    if request.method == 'POST':
        name = request.POST.get('name', 'Guest')
        return HttpResponse(f"Hello, {name}!")
    else:
        return HttpResponse("Please submit the form.")
This example reads query parameters from the URL.
Django
from django.http import HttpResponse

def show_query(request):
    search = request.GET.get('q', '')
    return HttpResponse(f"You searched for: {search}")
Sample Program

This simple view reads a 'name' from the URL query and greets the user. If no name is given, it says 'Friend'.

Django
from django.http import HttpResponse

def greet_user(request):
    # Check if user sent a name via GET
    name = request.GET.get('name', 'Friend')
    # Return a greeting message
    return HttpResponse(f"Hello, {name}!")
OutputSuccess
Important Notes

The HttpRequest object is your main way to get info about what the user sent.

Always check request.method to know if data comes from GET or POST.

Use request.GET for URL query data and request.POST for form data.

Summary

The HttpRequest object holds all details about a user's web request.

You use it in your view functions to read data like form inputs, query strings, and headers.

It helps your app respond correctly based on what the user sends.