A view function is simply a function that gets called by Django when a user navigates to a particular page on a website.
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.
To give you some context, let’s see explicitly what happens when a user makes a request on the webserver or webpage.
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")
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.
View all Courses