How to create a view function in Django

A view function is simply a function that gets called by Django when a user navigates to a particular page on a website.

Working of a view function

A user might want to visit a particular web page like //127.0.0.1.1:800/shots after successfully creating an app in Django and having successfully launched the Django home page with a webserver (//127.0.0.1.1:800/ by default). The browser then sends an HTTP request to our web server.

At this point, Django takes that request, inspects the URL or the address, and it figures out that the user wants to see the “shots” section on the web page, so it calls a view function.

The job of this function is to return the response to the browser or the user.

In essence, the view function dynamically generates some HTML mark-up (“shots” in this case) to be returned to the user. The browser will simply get the HTML and display it to the user.

Working of the view function
Working of the view function

Step-by-step process

To give you some context, let’s see explicitly what happens when a user makes a request on the webserver or webpage.

  1. A user makes a request for any of your Django web pages like //127.0.0.1.1:800/shots.
  2. The request is received by the web server.
  3. The web server passes the request to Django.
  4. Django inspects the URL paths in your Django app to pick which view to use.
  5. The view function then determines which models are needed and passes them to the template (this can include HTML, XML documents, or an image)
  6. The template is simply used to generate the page’s HTML.
  7. Finally, the generated HTML is passed back to the user’s browser as a response.

Creating the view function

Under the App folder of your Django project, open the file called views.py and key in the command below:

from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return HttpResponse ("Hello world")

Explanation

  • Line 1: we imported a class called HttpResponse. With this class, we can create an HttpResponse to return to the user

  • Line 2: Django is the project, the shortcut is the module, and we are importing the render function.

  • Line 4: We defined a function called index(). It doesn’t really matter what we call it, but by convention we use the word index for the main page of an App. We passed a parameter request to the function; this is the HttpResponse that is passed to the view function.

  • Line 5: We returned an instance of the class HttpResponse(), and with an argument to the Constructor we passed "Hello world". This is what the user gets to see on the webpage of the browser. Be that as it may, the constructor can also have HTML stored in the template as an argument.

Free Resources