Learn Django

Create the "Hello, World" Web App

An introductory programming course wouldn't be complete without a "Hello, World" application. In this lesson, you'll learn how to render those words on a web page.

While Django is known for its advanced capability, it can also be slimmed down to a very simple application. Rendering the worlds 'Hello, World' in a browser requires just a small subset of the frameworks feature set. In the steps below you'll learn how to get a slimmed down version of Django running, with just enough functionality to render text in a browser.

Step 1: Open the Project

Using the IDE you installed in the 'Computer Setup' chapter, open the hello-world directory in your IDE.

Step 2: Create the hello.py File

Create a file named hello.py in the root of the hello-world directory. The file location should be /.../hello-world/hello.py. Open this file in your IDE for editing.

Step 3: Configure Required Django Settings

Django projects have a settings file that contains all the system level settings required to run a project. In a production application there could be dozens of settings. However, there are but a few settings that Django absolutely needs to have for a minimal installation. According to the documentation, you can configure these settings with the settings.configure() command.

Here we'll explore the basic settings required.

First, the DEBUG setting needs to be set. This will tell Django what to do when it encounters an error. If the value is set to True, Django will render helpful error pages in your browser. If set to False, those error pages will be hidden and a more generic error message will rendered.

The second required setting is the SECRET_KEY. Django's documentation says this key "...is used to provide cryptographic signing, and should be set to a unique, unpredictable value." In a normal Django project this key would be a randomly generated value containing letters, numbers, and special characters. In this sample project we're setting our own key for demonstration purposes.

The last required setting is the ROOT_URLCONF value. This is a pointer to the file containing the URL configuration rules. In normal project this is a separate file containing a series of rules for each page in our application. In the example below we're assigning the value sys.modules[__name__] which basically says the URL configurations will be in this file (and will be added in the next step).

Add the following code to your hello.py file.

1
2
3
4
5
6
7
8
9
import sys

from django.conf import settings 

settings.configure(
    DEBUG=True,
    SECRET_KEY='thisisabadkeybutitwilldo',
    ROOT_URLCONF=sys.modules[__name__],
)

Step 4: Configure the URL

As URLs are the entry point into Django applications, even an application as simple as ours needs to have at least one URL configuration rule. In the below step you'll build off the code already in your file.

In the updated code below you'll notice that we added the urlpatterns variable. This is a list of URL patterns. Here, we're creating just one pattern, /hello-world/, that users will be able to access when the application is fully built.

New or modified lines are highlighted in yellow.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import sys

from django.conf import settings 
from django.conf.urls import patterns

settings.configure(
    DEBUG=True,
    SECRET_KEY='thisisabadkeybutitwilldo',
    ROOT_URLCONF=sys.modules[__name__],
)

urlpatterns = patterns('',
    (r'^hello-world/$', index),
)

Step 5: Configure the View

In the previous step you configured the URL. On line 13 in that code you'll notice that the /hello-world/ URL was created. After that is the word index. That's the name of the view that we need to create. Views are Python functions (or as you'll learn later, can be Python classes as well) that are executed when a certain URL is accessed. In our sample application we now need to create a Python function named index. This function is extremely basic; all it does is return an HTTP response with the text 'Hello, World'.

Add the following code to your existing file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import sys

from django.conf import settings 
from django.conf.urls import patterns
from django.http import HttpResponse

settings.configure(
    DEBUG=True,
    SECRET_KEY='thisisabadkeybutitwilldo',
    ROOT_URLCONF=sys.modules[__name__],
)

def index(request):
    return HttpResponse('Hello, World')

urlpatterns = patterns('',
    (r'^hello-world/$', index),
)

Step 6: Enable Command Line Support

Django comes with a utility called execute_from_command_line that can be used to run the development web server from the command line. In this step we'll add a little bit of code that will tell our application that if this file is the main script file, it should use the execute_from_command_line utility.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import sys

from django.conf import settings 
from django.conf.urls import patterns
from django.http import HttpResponse
from django.core.management import execute_from_command_line

settings.configure(
    DEBUG=True,
    SECRET_KEY='thisisabadkeybutitwilldo',
    ROOT_URLCONF=sys.modules[__name__],
)

def index(request):
    return HttpResponse('Hello, World')

urlpatterns = patterns('',
    (r'^hello-world/$', index),
)

if __name__ == "__main__":
    execute_from_command_line(sys.argv)

Step 7: Verify It Works

The last step is to verify that it all works. Go to your terminal, navigate to the hello-world folder, and make sure the virtual env is activated. Then run the following command.

When you run this command you'll see a warning message. You can ignore that for now.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
(venv)$ python hello.py runserver
Performing system checks...

System check identified some issues:

WARNINGS:
?: (1_7.W001) MIDDLEWARE_CLASSES is not set.
    HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. If your project needs these middleware then you should configure this setting.

System check identified 1 issue (0 silenced).
November 22, 2014 - 07:41:17
Django version 1.7.1, using settings None
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Go to a web browser and access this URL: http://127.0.0.1:8000/hello-world/. The worlds 'Hello, World' should display.

You've just built your first Django application!

References

Here are several references I used in the writing of this lesson:
Simplifying Django by Meghan Blanchette
Mini-Django by Tim Watts
Minimal Django by Olifante

Track your progress with a free account