Request and Response in Django

Search for a command to run...

Thanks for the article!
This series will cover the core concepts on web application development using Django, from basic installation to user authentications and some core concepts. Status: 9/14 published ✅
When working with web frameworks at some point rendering data directly through your controller or views is not efficient. Let's take an example of code snippet from our first article in this series Django Setup, Architecture and Hello World which loo...
Nothing serious, just experimenting on Django Framework

Working with simple media uploads and serving these media files

Using static files like JavaScript, CSS, images with Django

Class() based views in Django

function() based views in Django

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 i.e print(type(request)) # must be HttpRequest class).
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
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:
request.path in our view function, which give us path i.e: /profile/)request.method in our view function, which gives us Uppercase request method i.e: GET, POST, HEAD)request.GET in our view function, which gives us all HTTP GET parameters in dict like object)request.POST in our view function, which gives us all HTTP POST parameters in dict like object)request. [Text](Link) FILES in our view function, which gives us all uploaded files from HTML form in a dict like object)request.headers in our view function, which gives us all HTTP headers in a dict like object)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.
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 ")
response.write("world")
It is also possible to have a JSON encoded response.
from django.http import JsonResponse
response = JsonResponse({"message":"Hi from djangotherightway.com"})
But, remember everything under the hood is a
HttpResponse()
complete example,
from django.http import JsonResponse
def message_view(request):
return JsonResponse({"message":"Hi from djangotherightway.com"})
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)
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")
else:
return HttpResponse("Page found")
def home_view(request):
if request.method == 'GET':
# do something for GET
elif request.method == 'POST':
# do something for POST here
else:
# fallback? or and error response?
from django.http import HttpResponse
def home_view(request):
if some_condition:
return HttpResponse(status=403) # 403 means permission denied
else:
return HttpResponse(status=200) # 200 means OK
response to a client request404 means it lies to Client error group and 404 means Page Not Found500 means it lies to Server error group and 500 means Internal Server ErrorNow being a backend engineer there lies a confusion, on how to select a status code. Actually this totally depends on the situation you are in and the requirements you are in(
has nothing to do with web framework or stacks you are working on) but we always should follow a standard widely accepted by the community. Let's try to understand it more with an example;
- Status code 3XX means
Redirectioncategory, to be more specific let's assume308status code which meansPermanent Redirection. So to inform a client of a redirection you simply respond with a308status code and aLocationto where the client should redirect. This way client simply performs a redirection because client knows the use case of308status code. But what is a client? Is't this a client side software created by engineers? So, it's a client side engineer duty to implement those, but what if we make changes on status code(maybe 200 instead of 308) to perform this same operation? This is also possible- To perform the same redirection work, now server will send
200status code with some data{'redirect_to':'https://djangotherightway.com'}. This way on the client side we simply implement a logic where we check forredirect_urlon200 statusand implement redirection. On a JS client side you will redirect a user to other location using a simple codewindow.location.replace("https://djangotherightway.com");
So, does this mean we can use any status code for performing operations? The simple answer would be No, this is a suggestion only and my suggestion is Let's follow standards to make our community much more stronger, but what about the example i just explain above? Well, some case might arise up when you need to customize according to your need and may need to skip the standard but try to be on the standard as much as possible
Standard Matters because since 3XX means a redirection have you ever noticed your browser will automatically redirect you to another location incase your browser gets 3XX. Browser does this for making user experience good and doesn't mean browser will react on every status code they see from the server.
Do you want to see this browser behaviour in action? type https://djangotherightway.com/learn in the browser and you will be redirected to https://djangotherightway.com/series/learn all with the help of a simple status code 301 which means Moved Permanently