Request and Response in Django

Subscribe to my newsletter and never miss my upcoming articles

When a page is requested, Django under the hood created a HttpRequest object, this HttpRequest object contains meta information about the request. This is the same request object we talked when we created our view function def profile_view(request):... (check type of request to confirm). When a view function receives a HttpRequest object as its first argument, this view function must return and HttpResponse object.

A sample view,

def profile_view(request):             # first parameter HttpRequest Object
    return HttpResponse("Hello World") # view returned HttpResponse Object
The HttpRequest object

Many of us might just ignore this Request object thinking its of no use, but trust me there are lots of meta information about our request, which we may need in our program/view function to properly execute our logic.

Some of the attributes and methods of HttpRequest objects are:

  1. HttpRequest.path (request.path in our view function, which give us path i.e: /profile/)
  2. HttpRequest.path (request.method in our view function, which gives us Uppercase request method i.e: GET, POST, HEAD)
  3. HttpRequest.GET (request.GET in our view function, which gives us all HTTP GET parameters in dict like object)
  4. HttpRequest.POST (request.POST in our view function, which gives us all HTTP POST parameters in dict like object)
  5. HttpRequest.FILES (request.FILES in our view function, which gives us all uploaded files from HTML form in a dict like object)
  6. HttpRequest.headers (request.headers in our view function, which gives us all HTTP headers in a dict like object)
  7. HttpRequest.user (request.user in our view function, which gives us currently authenticated user. This attribute is set from middleware. We will look into this in later section of our series)

It consist of some useful methods as well i.e: HttpRequest.get_host() HttpRequest.get_port() HttpRequest.is_secure() #https or not which you can try and experiment yourself.

The HttpResponse object

We learnt about HttpRequest object, which was automatically created by the Django itself and get passed to the view function. But on the other hand, its our duty as a programmer to return and HttpResponse object from view function like we did in previous example.

from django.http import HttpResponse

response = HttpResponse("Hello World")

we can also add our content incrementally

response = HttpResponse()
response.write("hello ")
Returning 404 errors from HttpResponse

Every Http response must have a status code. 404 is one of the status code frequently used to denote that the requested page was not found

from django.http import HttpResponse, HttpResponseNotFound

def home_view(request):
    if some_condition:
        return HttpResponseNotFound("Page not found")
        return HttpResponse("Page found")
JsonResponse object

It is also possible to have a JSON encoded response.

from django.http import JsonResponse

response = JsonResponse({"message":"Hi from"})

complete example,

from django.http import JsonResponse

def message_view(request):
  return JsonResponse({"message":"Hi from"})

if you want to serialize and response non-dict objects then make sure you include safe=False in JsonResponse JsonResponse([1,2,3],safe=False)

  • Finding our request method in our view function
def home_view(request):
    if request.method == 'GET':
        # do something for GET
    elif request.method == 'POST':
        # do something for POST here
        # fallback? or and error response?
  • Returning custom HTTP status code
from django.http import HttpResponse

def home_view(request):
    if some_condition:
        return HttpResponse(status=403) # 403 means permission denied 
        return HttpResponse(status=200) # 200 means OK

No Comments Yet