4. Django views

A Django view function, or view for short, is a Python function that takes a Web request and returns a Web response.

This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image … or anything, really. The view itself contains whatever arbitrary logic is necessary to return that response.

This code can live anywhere you want, but the convention is to put views in a file called views.py, placed in your project or application directory.

Django uses request and response objects to pass state through the system.

When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object. More information on these at https://docs.djangoproject.com/en/3.0/ref/request-response/

This is a very simple views.py file which returns some html.

from django.http import HttpResponse

def simple_view(request):
    html = "Hello world!"
    return HttpResponse(html)

Let’s edit our little simple view so that we can access the IP address of the requesting client and show it to the user.

We want the HTTP request header data and that’s stored in an object called meta within the request object, and then from the header we’ll retrieve the IP address, which is a dict with a key called remote address. Then if we want to show remote address to our user, we can edit our little toy HTML Document, “Your IP address is,”

def simple_view(request):
    header = request.META
    ip = header['REMOTE_ADDR']
    html = "Your IP Address is: "+ip+""
    return HttpResponse(html, content_type='text/html')
Wednesday 20 October 2021, 33 views


Leave a Reply

Your email address will not be published. Required fields are marked *