Thursday, January 5, 2017

Django - 006 - Our first Django Powered web page

If you were publishing a simple Hello World web page without a web framework, you would simply time Hello World into a text file, call it hello.html, and upload it to a directory on a web server somewhere. Notice in that process you have specified two key pieces of information about that webpage:

  1. its contents (the string Hello World) and
  2. its URL (for example, http://www.example.com/hello.html)


With Django, you specify the same two things, but in a different way. The contents of the page are produced by a view function, and the URL is specified in a URLconf.

Our first View

Within the myD3site directory that we created earlier, create a empty file called views.py. This python module will contain our views for now. Our Hello World view is simple. Here is the entire function, plus import statements, which you should type into the views.py file:

from django.http import HttpResponse

def hello(request):
  return HttpResponse("Hello World")

Let us step through this code one line at a time:

  • First, we import the class HttpResponse, which lives in the django.http module. We need to import this class because it is used later in our code.
  • Next, we define a function called hello - the view function.

Each view function takes atleast one parameter, called request by convention. This is an object that contains information about the current web request that has triggered this view, and is an instance of the class django.http.HttpRequest.

In this example, we do not do anything with request, but it must be the first parameter of the view nonetheless. Note that the name of the view function does not matter; it does not have to be named in a certain way in order for Django to recognize it. We are calling it hello here, because that name clearly indicates the gist of the view, but it could just as well be named hello_wonerful_beautiful_world, or something equally revolting. The next section, Your first URLconf, will shed light on how Django finds this function.

The function is a simple one-liner: it merely returns an HttpResponse object that has been instantiated with the text Hello world.

The main lesson here is this:
a view is just a python function that takes an HttpRequest as its first parameter and returns an instance of HttpResponse. In order for a Python function to be a Django view, it must do these two things. (There are exceptions, but we will get to those later.)


No comments:

Post a Comment